Java Reference
In-Depth Information
return y;
}
}
6.17
Given two method definitions,
public static double m( double x, double y)
public static double m( int x, double y)
tell which of the two methods is invoked for:
a. double z = m( 4 , 5 );
b. double z = m( 4 , 5.4 );
c. double z = m( 4.5 , 5.4 );
6.9 The Scope of Variables
The scope of a variable is the part of the program where the variable can be
referenced.
Key
Point
Section 2.5 introduced the scope of a variable. This section discusses the scope of vari-
ables in detail. 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 in Figure 6.5.
scope of variables
local variable
public static void method1() {
.
.
for ( int
i
= 1 ; i < 10 ; i++) {
.
.
The scope of i
int j ;
.
.
.
The scope of j
}
F IGURE 6.5
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 in different blocks in a method, but
you cannot declare a local variable twice in the same block or in nested blocks, as shown in
Figure 6.6.
 
 
 
Search WWH ::




Custom Search