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:
  1. Local Variables
  2. Instance Variables
  3. 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:
  • number is declared inside main()
  • 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:
  • rollNumber and name are 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 TypeDefault Value
int0
double0.0
booleanfalse
Stringnull
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 count is 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

FeatureLocalInstanceStatic
Declared InsideMethodClass (outside method)Class with static
Belongs ToMethodObjectClass
Default Value❌ No✅ Yes✅ Yes
Accessed UsingDirectlyObject referenceClass 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.
Learn Java Types of Variables | Java Course