This Java example demonstrates the usage of a local variable in Java with an example.
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
Comments
Post a Comment