Types of Variables in Java
1. Local Variables:
- Declared inside a method, constructor or block.
- Accessible only within the scope of where they are declared.
- Must be initialized before use.
Example :
public void display() {
int localVariable = 10; // Local variable
System.out.println(localVariable);
}
2. Instance Variables:
- Declared inside a class but outside any method, constructor or block.
- Each object of the class gets its own copy.
- Initialized to default values if not explicitly initialized.
Example :
public class Example {
int instanceVariable; // Instance variable
public static void main(String[] args) {
Example obj = new Example();
System.out.println(obj.instanceVariable); // Default value is 0
}
}
3. Static Variables:
- Declared using the static keyword.
- Shared among all instances of the class.
- Used to define constants or shared properties.
Example :
public class Example {
static int staticVariable = 5; // Static variable
public static void main(String[] args) {
System.out.println(Example.staticVariable);
}
}
0 Comments