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 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. But 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 in Figure 5.8.
You can declare a local variable with the same name multiple times in different non-nesting blocks in a method, but you cannot declare a local variable twice in nested blocks, as shown in Figure 5.9.
Caution
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 = ; 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. |