Variables in Java
Learn how to store and use information in your programs
Think of variables like labeled boxes in your room. Each box has a name (like 'Toys' or 'Books'), and you can put things inside, take them out, or change what's in them. Variables work the same way - they're named containers that store information!
What is a Variable?
A variable is a named storage location in memory that holds a value. You can think of it as a box with a label.
// Variable declaration and initializationint age; // Declaration: creates a box labeled "age"age = 15; // Initialization: puts value 15 in the box// Or do both at onceint score = 100; // Declare and initialize together// You can change the value laterscore = 95; // Changes the value from 100 to 95score = score + 5; // Changes to 100 (95 + 5)📝 Variable Naming Rules
Follow these rules when naming variables:
- ✓Must start with a letter, $ or _ (not a number!)
- ✓Can contain letters, numbers, $ and _
- ✓Cannot use Java keywords (like int, class, public)
- ✓Case-sensitive: myVariable and MyVariable are different
- ✓Use meaningful names: 'studentAge' not 'x'
✅ Good vs ❌ Bad Variable Names
// ✅ GOOD - Clear and descriptiveint studentAge = 18;String firstName = "Alice";double averageScore = 85.5;boolean isRegistered = true;// ❌ BAD - Unclear or breaking rulesint a = 18; // Too short, unclearString 1name = "Bob"; // Starts with number (ERROR!)double avg$ = 85.5; // $ is allowed but not recommendedboolean x = true; // Too vague// ✅ GOOD - Following conventionsfinal int MAX_STUDENTS = 100; // Constant in UPPERCASEint totalCount = 0; // camelCase for variablesString userName = "john"; // camelCase for multi-word// ❌ BAD - Not following conventionsint Max_Students = 100; // Wrong style for constantint TotalCount = 0; // Should start with lowercaseString user_name = "john"; // Should use camelCase not snake_case🔧 Types of Variables in Java
Java has different kinds of variables based on where they're declared and how long they live:
Local Variables
Declared inside a method. Only exists while the method is running.
💡 Like items on your desk - only there while you're working
⏱️ Created when method starts, destroyed when method ends
Instance Variables
Declared in a class but outside methods. Each object has its own copy.
💡 Like each person having their own name and age
⏱️ Lives as long as the object exists
Static Variables
Shared by all objects of a class. Only one copy exists.
💡 Like the school name - same for all students
⏱️ Lives for the entire program execution
📝 Code Examples: Variable Types
public class Student { // INSTANCE VARIABLES (different for each student) String name; // Each student has their own name int age; // Each student has their own age double gpa; // Each student has their own GPA // STATIC VARIABLE (shared by all students) static String schoolName = "Oak Valley High"; // Same for everyone! static int studentCount = 0; // Counts all students // Constructor public Student(String name, int age, double gpa) { this.name = name; this.age = age; this.gpa = gpa; studentCount++; // Increases for each new student } public void displayInfo() { // LOCAL VARIABLES (only exist in this method) String message = "Student Info:"; // Created when method starts int currentYear = 2024; // Only accessible here System.out.println(message); System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("School: " + schoolName); // message and currentYear are destroyed when method ends } public static void main(String[] args) { // Creating students Student alice = new Student("Alice", 16, 3.8); Student bob = new Student("Bob", 17, 3.5); alice.displayInfo(); bob.displayInfo(); // Static variable - same for all System.out.println("Total students: " + Student.studentCount); // 2 System.out.println("School: " + Student.schoolName); // Oak Valley High // Each student has different instance variables System.out.println("Alice's GPA: " + alice.gpa); // 3.8 System.out.println("Bob's GPA: " + bob.gpa); // 3.5 }}🎯 Variable Scope (Where Can I Use My Variable?)
Scope means where in your code you can see and use a variable:
Method Scope
Variable exists only inside the method
💡 Like a recipe ingredient - only used while cooking that dish
Class Scope
Variable accessible throughout the class
💡 Like items in your bedroom - you can use them anywhere in your room
Block Scope
Variable exists only inside {} braces
💡 Like toys in a specific drawer - only accessible when that drawer is open
📝 Code Examples: Variable Scope
public class ScopeDemo { // CLASS SCOPE - accessible throughout the class int classVariable = 100; public void method1() { // METHOD SCOPE - only accessible in this method int methodVariable = 200; System.out.println(classVariable); // ✓ Can access System.out.println(methodVariable); // ✓ Can access // BLOCK SCOPE - only inside the if block if (classVariable > 50) { int blockVariable = 300; System.out.println(blockVariable); // ✓ Can access here } // System.out.println(blockVariable); // ❌ ERROR! Out of scope } public void method2() { System.out.println(classVariable); // ✓ Can access // System.out.println(methodVariable); // ❌ ERROR! Different method } public static void main(String[] args) { // Loop variable scope for (int i = 0; i < 5; i++) { int loopVar = i * 2; System.out.println("i = " + i + ", loopVar = " + loopVar); } // System.out.println(i); // ❌ ERROR! i only exists in loop // System.out.println(loopVar); // ❌ ERROR! loopVar only in loop // Block scope example { int x = 10; System.out.println(x); // ✓ Works here } // System.out.println(x); // ❌ ERROR! x only exists in block above }}🔒 Final Variables (Constants)
Variables that never change - like your birthday!
public class FinalDemo { // Final variable - cannot be changed after initialization final int DAYS_IN_WEEK = 7; final double PI = 3.14159; final String SCHOOL_NAME = "Oak Valley High"; public static void main(String[] args) { // Local final variable final int MAX_SCORE = 100; System.out.println("Max score: " + MAX_SCORE); // MAX_SCORE = 200; // ❌ ERROR! Cannot change final variable // Final reference variable final int[] numbers = {1, 2, 3, 4, 5}; numbers[0] = 99; // ✓ Can modify array contents System.out.println(numbers[0]); // 99 // numbers = new int[]{6, 7, 8}; // ❌ ERROR! Cannot reassign final reference // Convention: Use UPPERCASE for constants final double GRAVITY = 9.8; final int SPEED_OF_LIGHT = 299792458; }}✨ Best Practices
- ✓Use descriptive names: 'studentCount' not 'sc'
- ✓Start with lowercase, use camelCase: myVariableName
- ✓Constants in UPPERCASE: MAX_SIZE, PI
- ✓Initialize variables before using them
- ✓Keep variables in the smallest scope possible
- ✓Use final for values that shouldn't change
💼 Interview Tips
- 💡Know the difference between declaration and initialization
- 💡Understand variable scope - very common interview question!
- 💡Remember: local variables must be initialized before use
- 💡Instance variables get default values (0, false, null)
- 💡Static variables belong to the class, not objects
- 💡Be ready to explain the difference between instance and static variables
⚠️ Common Mistakes
- ✗Using a variable before declaring it
- ✗Using a local variable before initializing it
- ✗Declaring variables with names that are too short or unclear
- ✗Using same variable name in nested scopes (can be confusing)
- ✗Forgetting that variables declared in if/for blocks are not accessible outside
- ✗Not understanding the difference between primitive and reference variable assignment