Types of Variables
3 min read ·
In Java, variables are classified based on where they are declared and how they are used.
There are mainly three types of variables:
- Local Variables
- Instance Variables
- Static Variables
Let’s understand each one properly with runnable examples.
1) Local Variables
A local variable is declared inside a method, constructor, or block.
- It can only be used inside that method.
- It must be assigned a value before use.
- It does not have a default value.
Example
Here:
numberis declared insidemain()- It cannot be accessed outside
main()
If you try to use it outside the method, it will give an error.
2) Instance Variables
Instance variables are declared inside a class but outside any method.
- They belong to an object.
- Each object gets its own copy.
- They get default values if not assigned.
Example
Here:
rollNumberandnameare instance variables.- They are accessed using object reference
s1.
Each new object will have its own values.
Default Values of Instance Variables
If you don’t assign values, Java gives default values:
| Data Type | Default Value |
|---|---|
| int | 0 |
| double | 0.0 |
| boolean | false |
| String | null |
Example:
Output:
0
null
3) Static Variables
Static variables are declared using the
static keyword.- They belong to the class, not objects.
- Only one copy is shared by all objects.
- Memory is allocated only once.
Example
Output:
3
Explanation:
- Each time an object is created, constructor increases
count. - Since
countis static, all objects share the same variable. - Final value becomes 3.
Accessing Static Variables Without Object
You can access static variables using class name.
This is the recommended way.
Quick Comparison
| Feature | Local | Instance | Static |
|---|---|---|---|
| Declared Inside | Method | Class (outside method) | Class with static |
| Belongs To | Method | Object | Class |
| Default Value | ❌ No | ✅ Yes | ✅ Yes |
| Accessed Using | Directly | Object reference | Class name |
Understanding these three types is very important because:
- Local variables are used for temporary logic.
- Instance variables store object data.
- Static variables store shared data.
These concepts are heavily used in real world Java applications and OOP programming.