- In Java, variables are classified based on where they are declared and where they can be accessed.
Local Variable:
- A local variable is declared inside a method, constructor, or block.
- Declared inside { } of a method or block.
- Accessible only inside that method/block.
- Must be initialized before use
- Lifetime exists only while method executes
class Demo {
void show() {
int x = 10; // local variable
System.out.println("Value of x: " + x);
}
public static void main(String[] args) {
Demo obj = new Demo();
obj.show();
}
}
Global Variable (Instance Variable in Java)
-
In Java, there is no true global variable like in C/C++.
Instead, we use:1)Instance Variable (Non-static)
2)Static Variable (Class variable)
These are commonly called "global variables".
1) Instance Variable:
- Declared inside class but outside methods.
- Accessible by all methods of the class.
- Each object gets its own copy.
- Gets default value (0, null, false).
class Demo {
int y = 20; // instance variable
void display() {
System.out.println("Value of y: " + y);
}
public static void main(String[] args) {
Demo obj = new Demo();
obj.display();
}
}
2)Static Variable(Class Variable)
- Declared using static keyword.
- Shared among all objects.
- Accessed using class name.
class Demo {
static int z = 30; // static variable
public static void main(String[] args) {
System.out.println("Value of z: " + Demo.z);
}
}
Top comments (0)