1. The Hook (The "Byte-Sized" Intro)
- In a Nutshell: Variables = containers for data.
- Declaration: int age; (type + name).
- Initialization: age = 25; (assign value).
- Combined: int age = 25;. 3 types: Local (method scope, no default value), Instance (object scope, has default), Static (class scope, shared by all instances).
- Scope: Where variable is visible (block, method, class).
- Naming: camelCase, descriptive.
- Golden rule: Initialize before use. Local variables MUST be initialized!
Think of labeled boxes. Declaration = get empty box, write label. Initialization = put item in box. Local variable = box in your desk (private to you). Instance variable = box in your room (you own it). Static variable = shared locker (everyone uses same box)!
2. Conceptual Clarity (The "Simple" Tier)
💡 The Analogy
- Declaration: Create labeled container
- Initialization: Fill the container
- Local Variable: Personal workspace (desk drawer)
- Instance Variable: Personal storage (bedroom closet)
- Static Variable: Shared resource (company supplies)
3. Technical Mastery (The "Deep Dive")
java
// ===========================================
// 1. DECLARATION AND INITIALIZATION
// ===========================================
// Declaration (reserve memory, no value yet)
int age;
String name;
double salary;
// Initialization (assign value)
age = 25;
name = "Alice";
salary = 75000.50;
// Combined (declare + initialize)
int count = 0;
String message = "Hello";
double pi = 3.14159;
// Multiple variables (same type)
int x, y, z; // Declare three
int a = 1, b = 2, c = 3; // Declare and initialize
// ❌ BAD: Using before initialization
int value;
System.out.println(value); // ❌ Compile error!
// ✅ GOOD: Initialize before use
int value = 10;
System.out.println(value); // ✅ Works
// ===========================================
// 2. LOCAL VARIABLES (Method Scope)
// ===========================================
class Example {
void calculateTotal() {
// Local variables (exist only in this method)
int quantity = 5; // Local to calculateTotal()
double price = 19.99; // Local to calculateTotal()
double total = quantity * price;
System.out.println(total);
} // quantity, price, total destroyed here
void anotherMethod() {
// System.out.println(quantity); // ❌ Error! quantity not visible
}
}
// Local variables:
// - ✅ Declared inside method/block
// - ✅ Must be initialized before use
// - ✅ No default values
// - ✅ Destroyed when method exits
// - ❌ Cannot use access modifiers (public, private, etc.)
// ===========================================
// 3. INSTANCE VARIABLES (Object Scope)
// ===========================================
class Student {
// Instance variables (belong to each object)
String name; // Default: null
int age; // Default: 0
double gpa; // Default: 0.0
boolean active; // Default: false
void showInfo() {
// Can access instance variables without declaration
System.out.println(name); // Each object has its own
System.out.println(age);
}
}
// Usage:
Student alice = new Student();
alice.name = "Alice"; // Alice's name
alice.age = 20; // Alice's age
Student bob = new Student();
bob.name = "Bob"; // Bob's name (different from Alice's)
bob.age = 22;
// Instance variables:
// - ✅ Declared at class level (outside methods)
// - ✅ Have default values (0, false, null)
// - ✅ Each object has its own copy
// - ✅ Can use access modifiers (private, public, protected)
// - ✅ Destroyed when object is garbage collected
// ===========================================
// 4. STATIC VARIABLES (Class Scope)
// ===========================================
class Counter {
// Static variable (shared by ALL objects)
static int count = 0; // Only ONE copy for entire class
// Instance variable (each object has own copy)
String name;
Counter(String name) {
this.name = name;
count++; // Increment SHARED counter
}
}
// Usage:
Counter c1 = new Counter("First"); // count = 1
Counter c2 = new Counter("Second"); // count = 2
Counter c3 = new Counter("Third"); // count = 3
System.out.println(Counter.count); // 3 (shared by all)
// Static variables:
// - ✅ Declared with 'static' keyword
// - ✅ Shared by ALL instances of class
// - ✅ Can access without creating object
// - ✅ Initialized when class is loaded
// - ✅ Destroyed when program ends
// ===========================================
// 5. VARIABLE SCOPE
// ===========================================
class ScopeDemo {
// Class scope (instance variable)
int instanceVar = 10;
// Class scope (static variable)
static int staticVar = 20;
void method() {
// Method scope (local variable)
int localVar = 30;
// Block scope
{
int blockVar = 40;
System.out.println(blockVar); // ✅ Visible here
}
// System.out.println(blockVar); // ❌ Not visible here
// All visible in method
System.out.println(instanceVar); // ✅
System.out.println(staticVar); // ✅
System.out.println(localVar); // ✅
}
}
// ===========================================
// 6. VARIABLE SHADOWING
// ===========================================
class Shadowing {
int value = 10; // Instance variable
void method(int value) { // Parameter shadows instance variable
System.out.println(value); // 20 (parameter)
System.out.println(this.value); // 10 (instance variable)
}
}
Shadowing obj = new Shadowing();
obj.method(20);
// ===========================================
// 7. NAMING CONVENTIONS
// ===========================================
// ✅ GOOD: Descriptive, camelCase
int studentCount;
String emailAddress;
double accountBalance;
boolean isActive;
// ❌ BAD: Unclear, poor naming
int sc;
String ea;
double ab;
boolean a;
// ✅ GOOD: Boolean naming (is/has/can)
boolean isValid;
boolean hasPermission;
boolean canDelete;
// ❌ BAD: Boolean naming
boolean valid; // Unclear
boolean permission; // Sounds like object, not flag5. The Comparison & Decision Layer
| Variable Type | Scope | Default Value | Access | Lifetime |
|---|---|---|---|---|
| Local | Method/Block | None (must initialize) | Local only | Until method exits |
| Instance | Object | Yes (0, false, null) | Via object | Until object destroyed |
| Static | Class | Yes (0, false, null) | Via class/object | Until program ends |
6. The "Interview Corner" (The Edge)
The "Killer" Interview Question: "What's the difference between instance and static variables?" Answer:
Instance Variable (non-static):
- Each object has its own copy
- Accessed via object reference (
obj.var) - Different values for each instance
- Created when object is created
Static Variable:
- One copy shared by all objects
- Accessed via class name (
ClassName.var) - Same value for all instances
- Created when class is loaded
java
class Example {
int instanceVar; // Each object has own copy
static int staticVar; // ONE copy shared by all
}
Example e1 = new Example();
Example e2 = new Example();
e1.instanceVar = 10; // Only e1's copy
e2.instanceVar = 20; // Only e2's copy
Example.staticVar = 30; // Shared by e1 and e2
System.out.println(e1.staticVar); // 30
System.out.println(e2.staticVar); // 30 (same value!)Pro-Tips:
- Always initialize local variables:
java
// ❌ BAD
int count;
if (condition) {
count = 10;
}
System.out.println(count); // ❌ Might not be initialized!
// ✅ GOOD
int count = 0; // Always initialize
if (condition) {
count = 10;
}
System.out.println(count); // ✅ Always safe- Use 'this' to avoid shadowing confusion:
java
class Student {
String name;
void setName(String name) { // Parameter shadows field
this.name = name; // ✅ Clear: instance variable = parameter
}
}