In Java, variables are classified based on where they are declared and how they are accessed. The two main types are global (class-level) variables and local variables. Understanding their scope and behavior is essential for writing efficient programs.
What is a Global Variable in Java?
Java does not support true global variables like some other languages. Instead, it uses class-level variables, which behave similarly.
These variables are declared inside a class but outside any method.
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
What is a Local Variable?
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
- Declared inside method / block
- Accessible only within that method
- Memory created when method starts
- Destroyed when method ends
- Must be initialized before use


Top comments (0)