- Variables are used to store data in a Java program.
- Based on where a variable is declared and where it can be accessed, variables are classified as global variables and local variables.
What Are Global Variables in Java?
In Java, global variables are variables that are declared inside a class but outside all methods. They are accessible throughout the class and are also called instance variables or class (static) variables.
Key Points
- Declared at class level
- Accessible to all methods of the class
- Stored in heap memory (instance) or method area (static)
- Can be static or non-static
- Have default values
Example
class Student {
int age = 20; // global variable (instance)
static String school = "ABC School"; // global variable (static)
void display() {
System.out.println(age);
System.out.println(school);
}
}
- Here, age and school are global variables because they are accessible throughout the class.
What Are Local Variables in Java?
A local variable is declared inside a method, constructor, or block. It can be used only within that block.
Key Points
- Declared inside a method or block
- Accessible only within that scope
- Stored in stack memory
- No default value (must be initialized before use)
- Destroyed after method execution
Example
class Marks {
void show() {
int mark1 = 90; // local variable
System.out.println(x);
}
}
Top comments (0)