Java Reference
In-Depth Information
15
System.out.printf( "local x in main is %d%n" , x);
16
17
useLocalVariable(); // useLocalVariable has local x
18
useField(); // useField uses class Scope's field x
19
useLocalVariable(); // useLocalVariable reinitializes local x
20
useField(); // class Scope's field x retains its value
21
22
System.out.printf( "%nlocal x in main is %d%n" , x);
23
}
24
25
// create and initialize local variable x during each call
26
public static void useLocalVariable()
27
{
28
int x = 25 ; // initialized each time useLocalVariable is called
29
30
System.out.printf(
31
"%nlocal x on entering method useLocalVariable is %d%n" , x);
32
++x; // modifies this method's local variable x
33
System.out.printf(
34
"local x before exiting method useLocalVariable is %d%n" , x);
35
}
36
37
// modify class Scope's field x during each call
38
public static void useField()
39
{
40
System.out.printf(
41
"%nfield x on entering method useField is %d%n" , x);
42
x *= 10 ; // modifies class Scope's field x
43
System.out.printf(
44
"field x before exiting method useField is %d%n" , x);
45
}
46
} // end class Scope
local x in main is 5
local x on entering method useLocalVariable is 25
local x before exiting method useLocalVariable is 26
field x on entering method useField is 1
field x before exiting method useField is 10
local x on entering method useLocalVariable is 25
local x before exiting method useLocalVariable is 26
field x on entering method useField is 10
field x before exiting method useField is 100
local x in main is 5
Fig. 6.9 | Scope class demonstrates field and local-variable scopes. (Part 2 of 2.)
Method useField does not declare any local variables. Therefore, when it refers to x ,
field x (line 7) of the class is used. When method useField is first called (line 18), it out-
puts the value ( 1 ) of field x (lines 40-41), multiplies the field x by 10 (line 42) and outputs
Search WWH ::




Custom Search