5.5. Passing Parameters by Values

 
[Page 141 ( continued )]

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

Figure 5.8. A variable declared in the initial action part of a for loop header has its scope in the entire loop.


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.

Figure 5.9. A variable can be declared multiple times in non-nested blocks, but can be declared only once in nested blocks.
(This item is displayed on page 142 in the print version)

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.


 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net