Variables that are declared inside a method are called local variables because they can only be utilized and referenced in the method itself. Take a look at the code below showing the add()
method with a local variable inside.
package exlcode;
public class LocalVariableExample {
public static int exampleVariableOne = 10;
public static int exampleVariableTwo = 6;
public static void main(String[] args) {
System.out.println(add(exampleVariableOne, exampleVariableTwo));
// System.out.println(exampleVariableThree) will cause an error
// because exampleVariableThree is a local variable
}
public static int add(int x, int y) {
// this is a local variable
int exampleVariableThree = x + y;
return exampleVariableThree;
}
}
In the example, we cannot print exampleVariableThree
inside the main method because it exists only as a local variable in the add()
method. This is where we revisit the concept of access control. The local variable is only active and returns within the method in which it was declared. A local variable is not visible to any other method besides the one in which it exists. If you have a variable that will be used in multiple classes, you must make sure it is outside the method. If you are referencing a local variable outside of the method it exists in, you will get a compile-time error due to access control and visibility.
In cases where you will only use a variable in one method, keep it local by keeping it inside the method so that no other methods or classes can see or make any changes to it and alter your desired outcome.
Keep in mind that the parameters in a method are examples of and function as local variables.