When learning Java, one of the most important concepts to understand is how variables work. Among them, global variables and local variables play a key role in writing efficient and clean programs.
In this blog, we’ll break down these concepts in a simple and beginner-friendly way.
What Are Global Variables in Java?
Global variables in Java are variables that are declared inside a class but outside any method. They can be accessed by all methods within that class.
Types of Global Variables
- Non-Static Variables(Instance) – Belong to an object
- Static Variables – Shared across all objects
Example
class Demo {
int x = 10; // Instance variable
static int y = 20; // Static variable
void display() {
System.out.println(x);
System.out.println(y);
}
public static void main(String[] args) {
Demo obj = new Demo(); // create object
obj.display(); // call method
}
}
Step-by-step flow
- main() starts execution
- Object is created → Demo obj = new Demo();
- display() method is called
- Prints:
10 20
Key Characteristics
- Declared inside the class, outside methods
- Accessible throughout the class
- Automatically assigned default values
- Longer lifetime (until object or class exists)
What Are Local Variables in Java?
Local variables are declared inside a method, constructor, or block and can only be used within that specific area.
Example
class Demo {
void display() {
int a = 5;
System.out.println(a);
}
public static void main(String[] args) {
Demo obj = new Demo(); // create object
obj.display(); // call method
}
}
Output
Step-by-step flow
- main() starts execution
- Object is created
- display() is called
- Output:
5
Key Characteristics
- Declared inside methods or blocks
- Limited scope (only within method)
- No default values (must be initialized)
- Short lifetime (exists only during execution)


Top comments (0)