Java Local Variable Example


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

Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. These variables are declared inside a method of the class. Their scope is limited to the method which means that You can’t change their values and access them outside of the method.

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

Naming Convention

There are no specific rules for naming a local variable. All the rules of variables are applied to local variables.

Below mentioned are the rules for naming a local variable.
  • Variable names are case sensitive.
  • There is no limitation on the length of a local variable.
  • If a variable name is of one word only then all characters should be in lower case.

Reference

Comments