Java Reference
In-Depth Information
17
18 System.out.print("<");
19 writeSpaces(spaces1 * spaces2 - 5);
20 System.out.println(">");
21 }
22
23 // writes "number" spaces on the current output line
24
public static void
writeSpaces(
int
number) {
25
for
(
int
i = 1; i <= number; i++) {
26 System.out.print(" ");
27 }
28 }
29 }
In the first two lines of the
main
method, the computer finds instructions to allocate
and initialize two variables:
spaces1 3
spaces2 5
The next three lines of code produce an output line with three spaces bounded by
asterisks on either side:
System.out.print("*");
writeSpaces(spaces1);
System.out.println("*");
You can see where the asterisks come from, but look at the method call that pro-
duces the spaces. When Java executes the call on
writeSpaces
, it must set up its
parameter. To set up the parameter, Java first evaluates the expression being passed as
the actual parameter. The expression is simply the variable
spaces1
, which has the
value
3
. Therefore, the expression evaluates to
3
. Java uses this result to initialize a
local variable called
number
.
The following diagram indicates how the computer's memory would look as the
writeSpaces
method is entered the first time. Because there are two methods
involved (
main
and
writeSpaces
), the diagram indicates which variables are local
to
main
(
spaces1
and
spaces2
) and which are local to
writeSpaces
(the parameter
number
):
method
main
method
writeSpaces
spaces1
3
spaces2 5
number
3
Search WWH ::
Custom Search