What Is Default Value of Local Variable in Java?

Variables that are declared inside Methods in a Java program are called local variables.

Answer => "There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use."

Java Local Variable Example

In the following example, the sum local variable declared and initialized within a method:
package net.javaguides.corejava.variables;

public class LocalVariableExample {
    public int sum(int n) {
        int sum = 0;
        for (int i = 0; i < n; i++) {
            sum = sum + i;
        }
        return sum;
    }

    public static void main(String[] args) {
        LocalVariableExample localVariableExample = new LocalVariableExample();
        int sum = localVariableExample.sum(10);
        System.out.println("Sum of first 10 numbers -> " + sum);
    }
}
Output:
Sum of first 10 numbers -> 45

Key points about Local Variables

  • Local variables are declared in methods, constructors, or blocks.
  • Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block.
  • Access modifiers cannot be used for local variables.
  • Local variables are visible only within the declared method, constructor, or block.
  • Local variables are implemented at stack level internally.
  • There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use.

Comments