Variable Scope

Definition

The scope of a variable is the region in which that variable can be used. All Java variables have scopes.

Benefit

One benefit of scope is that it saves memory. Once a variable can no longer be used the computer can reclaim that memory for another use. Another benefit of having scopes is that it allows a programmer to reuse variable names. This becomes advantageous in a large program.

Methods

A variable's scope extends from its declaration to the termination of the block that most tightly encloses it. This means that, if a variable is declared within a method, it will exist through the end of that method, but not outside of it (this is because of Java's tactic for passing values. See Pass By Value).

public static void main (String[] args) {
  int a;
}
public static void meth2(int a) {
  int a;
}

In the above example, the two variables, both a, are completely unrelated.

Loops

The scope of a variable within a loop follow the same rules as above. If the variable is declared within the loop, it extends through the end of the loop. If, however, the variable is declared before the loop, it extends through the end of the method.

for(int inLoop = 0; inLoop < n; inLoop++) {
    //inLoop extends through the end of the loop
}
int beforeLoop;
for(beforeLoop = 0; beforeLoop < n; beforeLoop++) {
    //beforeLoop extends through the end of the method
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License