Java_Local&Global_Variable
Source: Dev.to
Local Variable
- Declared inside a method, constructor, or block (
{}). - Accessible only within that method or block.
- Must be initialized before use.
- Lifetime exists only while the method executes.
class Demo {
void show() {
int x = 10; // local variable
System.out.println("Value of x: " + x);
}
public static void main(String[] args) {
Demo obj = new Demo();
obj.show();
}
}
Global Variable (Instance Variable in Java)
Java does not have true global variables like C/C++. Instead, variables declared at the class level serve similar purposes.
Instance Variable (Non‑static)
- Declared inside a class but outside any method.
- Accessible by all methods of the class.
- Each object gets its own copy.
- Receives a default value (
0,null,false, etc.) if not explicitly initialized.
class Demo {
int y = 20; // instance variable
void display() {
System.out.println("Value of y: " + y);
}
public static void main(String[] args) {
Demo obj = new Demo();
obj.display();
}
}
Static Variable (Class Variable)
- Declared with the
statickeyword. - Shared among all instances of the class.
- Typically accessed using the class name.
class Demo {
static int z = 30; // static variable
public static void main(String[] args) {
System.out.println("Value of z: " + Demo.z);
}
}