1. Global Variable:
Java technically does not have "global variables" like C or Python.
But in Java, variables declared inside a class but outside methods are treated like global variables.
These are also called:
Instance variables
Class variables (if static)
Example:
class Student {
int age = 20; // Global Variable
void display() {
System.out.println(age);
}
public static void main(String[] args) {
Student obj = new Student();
obj.display();
}
}
Output:
20
Why This is Global Variable:
Because:
It is declared inside class
Outside method
Can be used in multiple methods
2.Local Variable:
A Local Variable is declared inside a method, constructor, or block.
It can only be used inside that method.
Example:
class Test {
void display() {
int num = 10; // Local Variable
System.out.println(num);
}
public static void main(String args[]) {
Test obj = new Test();
obj.display();
}
}
Output:
10
Top comments (0)