Types of Variables in Java with Examples: Local, Instance & Static
A variable in Java is a named container that holds data your program can use and modify. Java organizes variables into three categories based on where they are declared and how long they live: local, instance, and static. Understanding the difference is one of the first real building blocks toward writing correct, memory-efficient Java code.
Local Variables
Local variables are declared inside a method, constructor, or block, and they exist only for as long as that method is executing. They must be initialized before use since Java does not assign them a default value, and they are only accessible within the block where they were declared.
void calculateTotal() {
int quantity = 5; // local variable
double price = 49.99;
System.out.println(quantity * price);
}
Instance Variables
Instance variables are declared inside a class but outside any method. Each object of the class gets its own copy, so changing one object's instance variable does not affect another object's copy. Java automatically assigns them default values (0, null, false) if they aren't explicitly initialized.
Static Variables
Static variables belong to the class itself rather than any single object, which means every instance shares the exact same copy. They are declared using the static keyword and are commonly used for constants or values that should stay consistent across all objects, such as a counter tracking how many objects have been created.
- Local variables live only inside the method — fastest but most limited scope
- Instance variables live as long as the object exists, with a unique copy per object
- Static variables live for the lifetime of the class, shared across every object
- Only instance and static variables get automatic default values; local variables do not
Master Java with Uncodemy
Hands-on training, live projects, and placement support in our Java Programming Course.