Global Variable VS Local Variable
Source: Dev.to
Global Variable in Java
Java does not support true global variables. Instead, it uses class‑level variables, which behave similarly.
Types of Class‑Level Variables
- Static Variable → Shared by all objects
- Instance Variable → Separate copy for each object
Example
class Test {
static int x = 10; // class‑level (global‑like)
public static void main(String[] args) {
System.out.println(x);
}
}Output

Local Variable in Java
A local variable is declared inside a method, constructor, or block and can only be used within that scope.
Example
class Test {
public static void main(String[] args) {
int y = 5; // local variable
System.out.println(y);
}
}Output

Key Characteristics of Local Variables
- Declared inside a method or block
- Accessible only within that method/block
- Memory is allocated when the method starts and released when it ends
- Must be initialized before use