1️⃣ Local Variable
Variable declared inside a method, constructor, or block
class LocalExample {
void show() {
int a = 10; // local variable
System.out.println(a);
}
public static void main(String[] args) {
LocalExample obj = new LocalExample();
obj.show();
}
}
Key points
Works only inside the method
Must be initialized before use
Memory created when method is called
2️⃣ Global Variable (Instance Variable)
Variable declared inside class but outside methods
class GlobalExample {
int x = 20; // global (instance) variable
void display() {
System.out.println(x);
}
public static void main(String[] args) {
GlobalExample obj = new GlobalExample();
obj.display();
}
}
Key points
Belongs to object
Default value given (0, null, false)
Access using object
3️⃣ Static Variable
Variable declared using static keyword
Shared by all objects
class StaticExample {
static int count = 0; // static variable
StaticExample() {
count++;
}
public static void main(String[] args) {
new StaticExample();
new StaticExample();
new StaticExample();
System.out.println(count);
}
}
Output
3
Key points
Only one copy in memory
Access using class name
Memory allocated once
4️⃣ Non-Static Variable
Normal instance variable (without static)
class NonStaticExample {
int num = 5; // non-static variable
void show() {
System.out.println(num);
}
public static void main(String[] args) {
NonStaticExample obj1 = new NonStaticExample();
NonStaticExample obj2 = new NonStaticExample();
obj1.num = 10;
obj1.show(); // 10
obj2.show(); // 5
}
}
Key points
Each object has separate copy
Access using object
Different values for different objects
Top comments (0)