Variables in Java Explained: Local, Static, and Instance
Variables in Java
A variable is a symbolic name associated with a value. The value of a variable can change during program execution.
In Java, variables are classified into three types:
- Local Variable
- Static Variable
- Instance Variable
1. Local Variable
A local variable is declared inside a method, constructor, or block.
Key points:
- Also called a method-level variable
- Accessible only within the block {} where it is declared
- Does not support default values
- Must be initialized before use
- If declared but not initialized and used, it causes a compile-time error
- If declared but not used, no error is generated
Example:
void display() {
int x = 10; // local variable
System.out.println(x);
}
2. Static Variable
A static variable is declared inside a class but outside any method, using the static keyword.
Key points:
- Also called a class-level variable
- Supports default values
- Memory is allocated once and shared among all objects
- Can be accessed:
By variable name (within the same class)
By ClassName.variableName (from another class)
By ClassName.variableName (from another class)
Example:
class Example {
static int count = 5;
}
3. Instance Variable
An instance variable is declared inside a class but outside any method, without using the static keyword.
Key points:
Also called an object-level variable
Supports default values
Each object gets its own copy
Accessed using object creation
Example:
class Student {
int id; // instance variable
}
Variable Declaration and Initialization
Syntax:
dataType variableName = value;
Example:
int number = 10;
Initialization
Initialization is the process of assigning a value to a variable for the first time.
Reinitialization
Reinitialization is the process of assigning a new value to an already initialized variable.
The previous value is replaced
The new value is stored in the variable
Example:
int x = 5;
x = 10; // reinitialization
Comments
Post a Comment