DEV Community

Kesavarthini
Kesavarthini

Posted on

Java Variables

When learning Java, understanding how data is stored and accessed is just as important as learning syntax.
One of the key concepts behind this is variables.
In this blog, I’ll explain the different types of variables in Java—local, instance, and static—using simple explanations and examples suitable for beginners.

🔹 What is a Variable in Java?

A variable is a container used to store data values.
• The value of a variable can change during program execution
• Every variable has a data type
• Java is a strongly typed language

🔹 Types of Variables in Java

Java mainly has three types of variables:
1. Local Variables
2. Instance Variables
3. Static Variables

1️⃣ Local Variables
• Declared inside a class and method
• Accessible only within that method
• Must be initialized before use
• Stored in stack memory

Example:

class Test {
    void display() {
        int number = 10; // local variable
        System.out.println(number);
    }
}
Enter fullscreen mode Exit fullscreen mode

2️⃣ Instance Variables
• Declared inside a class but outside methods
• Each object has its own copy
• Default values are assigned automatically
• Stored in heap memory

Example:

class Student {
    int id;      // instance variable
    String name; // instance variable
}
Enter fullscreen mode Exit fullscreen mode

3️⃣ Static Variables
• Declared using the static keyword
• Shared among all objects of the class
• Memory allocated only once
• Stored in method area

Example:

class College {
    static String collegeName = "ABC College";
}
Enter fullscreen mode Exit fullscreen mode

🔹 Simple Program Showing All Types

class Example {
    int instanceVar = 20;
    static int staticVar = 30;

    void show() {
        int localVar = 10;

        System.out.println(localVar);
        System.out.println(instanceVar);
        System.out.println(staticVar);
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)