Local Variables in Java

Last Updated : 23 Jan, 2026

In Java, local variables are declared inside a method, a constructor, or a block and are used to store temporary data. They are created during execution and destroyed once the execution of the method or block completes. Its Key Characteristics are:

  • Scope: Accessible only within the method, constructor, or block where declared.
  • Lifetime: Exists only during the execution of the method or block.
  • Storage: Stored in stack memory for faster access.
  • Initialization: Do not have default values and must be explicitly initialized before use.

Syntax

dataType variableName = value;

Example 1: Local Variable Inside a Method

Java
class Test {
    void display() {
        int x = 10;  // Local variable
        System.out.println("Value of x: " + x);
    }

    public static void main(String[] args) {
        Test obj = new Test();
        obj.display();
    }
}

Output
Value of x: 10

Explanation:

  • x is a local variable declared inside the display() method.
  • It cannot be accessed outside this method.

Example 2: Local Variable Inside a Block

Java
class Example {
    public static void main(String[] args) {
        if (true) {
            int num = 50; // Local variable
            System.out.println(num);
        }
        // System.out.println(num); // Compile-time error
    }
}

Output
50

Explanation:

  • num is local to the if block.
  • Accessing it outside the block causes a compile-time error.

Example 3: Local Variables in Loops

Java
class LoopExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            System.out.println(i);
        }
        // i is not accessible here
    }
}

Output
1
2
3

Explanation:

  • i is a local variable of the for loop.
  • Its scope ends when the loop finishes execution.

Note:

  • Local variables must be initialized before use.
  • Java does not assign default values to local variables.
  • They cannot be declared static.
  • They are thread-safe because each thread has its own stack.
Comment