In Java, there are three main types of variables:
1. Local Variables
- Definition: Declared within a method, constructor, or block.
- Scope: Only accessible within the method or block where it is declared.
- Lifetime: Created when the method is called and destroyed when the method exits.
- Default Value: No default value, must be explicitly initialized.
- Example:
java
public void method() {
int localVar = 10; // Local variable
}
2. Instance Variables (Non-static Fields)
- Definition: Declared inside a class but outside any method or constructor. They are also called non-static fields.
- Scope: Each object has its own copy of instance variables.
- Lifetime: Created when an object is instantiated and destroyed when the object is destroyed.
- Default Value: Automatically initialized to default values (e.g.,
0
for numeric types,null
for object references). - Example:
java
class MyClass {
int instanceVar = 5; // Instance variable
}
3. Static Variables (Class Variables)
- Definition: Declared with the
static
keyword within a class, but outside any method or constructor. These are shared among all instances of the class. - Scope: Belong to the class, and only one copy exists, regardless of how many objects are created.
- Lifetime: Created when the class is loaded and destroyed when the class is unloaded.
- Default Value: Automatically initialized to default values like instance variables.
- Example:
java
class MyClass {
static int staticVar = 10; // Static variable
}