Page tags

Add a new page

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).

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(intinLoop = 0; inLoop < n; inLoop++){//inLoop extends through the end of the loop}

intbeforeLoop;
for(beforeLoop = 0; beforeLoop < n; beforeLoop++){//beforeLoop extends through the end of the method}