The Scope of Variables

The Scope of Variables

The scope of a variable is the part of the program where the variable can be referenced. A variable defined inside a method is referred to as a local variable. The scope of a local variable starts from its declaration and continues to the end of the block
that contains the variable. A local variable must be declared and assigned a value before it can be used.

A parameter is actually a local variable. The scope of a method parameter covers the entire method. A variable declared in the initial-action part of a for-loop header has its scope in the entire loop. However, a variable declared inside a for-loop body has its scope limited in the loop body from its declaration to the end of the block that contains the variable, as shown below:

You can declare a local variable with the same name in different blocks in a method, but you cannot declare a local variable twice in the same block or in nested blocks, as shown below:

A variable can be declared multiple times in non-nested blocks, but only once in nested blocks.

Do not declare a variable inside a block and then attempt to use it outside the block.
Here is an example of a common mistake:

for (int i = 0; i < 10; i++) {
}
System.out.println(i);

The last statement would cause a syntax error, because variable i is not defined outside of the for loop.

Leave a Reply

Your email address will not be published. Required fields are marked *