Java Variables Examples 3 – Local Variables

Local variables are designated inside some block of code that limits their scope.  That means the variable can only be set, accessed, or retrieved in the scope of the block.  In programming, these variables are only visible and editable in the block of code in which they are created. More specifically in Java:

Local Variables Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class. Java Variables Tutorial

Let’s look at an example:

In this example, we are in the class Bicycle with the method changeGear which takes input for the gear change (gearShift) and then outputs the new gear.  The new gear is a local variable (newGear) which is can only be used in the method.

Our example is fine for demonstrating a local variable but it’s not the only example of a local variable.   A local variable can be inside constructors, lambda’s, conditional blocks, etc.

Why keep variables local?

  1. Memory. In Java (and most languages) when a variable is local, it doesn’t have to remain in memory. This might increase performance.
  2. Safety. By “encapsulating” a variable, you keep it safe. It’s less likely that  you will accidentally change the value. Java’s encapsulation powers aren’t limited to local fields, private instance variables vary in usage, but follow similar principles.
  3. Ease of use. While points 1 and 2 definitely make coding Java easier, naming variables is really important. Picking the right, descriptive identifier is necessary to keep code legible and workable. Local variables make it easy to name them with simple and descriptive identifiers. Additionally, the type casting makes it easy to see what the variable does locally.

Written By StevenLacks