Java Reference
In-Depth Information
This fact explains why local variables do not retain their values from one
call of a method to the next call of the same method: all the information about
the first call is in a frame, and the frame is erased when the call is completed.
Suppose a call of method
m1
is being executed so that a frame for the call
exists. Suppose also that
m1
calls
m2
. A frame for the call is created so that there
are now two frames. If
m2
now calls a method
m3
, there will be three frames.
Of the three frames, the frame for
m3
will be erased first, then the frame for
m2
, and finally the frame for
m1
. This is because the call to
m3
is the first to com-
plete. The last frame to be created is the first to be erased, and the first frame to
be created is the last to be erased.
The creation and destruction of frames follows a last-in-first-out, or LIFO
discipline, and the frames may be maintained on what is called a
stack
.
A stack is a list of items with two operations for changing the list:
pushing
an item
onto the stack (inserting a new item on its top) and
popping an item
from
the top (removing the topmost item).
As an example of a stack, consider the stack of trays in a cafeteria. An
employee will load a large number of trays onto the top of the stack; then, peo-
ple take them off the top one at a time. The last one added by the employee is the
first one removed by a customer.
We show how a stack is used to maintain the frames for a series of calls.
Consider class
X
of Fig. 2.10, which contains two static methods. Assume that a
call
printLarger2(20, 6)
is about to be executed and that the call appears in a
method
m
. At this point, the stack of frames is as shown in the first (leftmost) dia-
gram in Fig. 2.11. The second diagram in Fig. 2.11 shows the situation just after
the frame for the call to
printLarger
has been created and the arguments have
been assigned to the parameters.
The first statement in the body of
printLarger2
is a call to procedure
printLarger
, so a frame for this call is created and pushed onto the stack of
frames. The third diagram in Fig. 2.11 shows the situation after this frame has
public class
X {
/**
Print the larger of
b
and
c */
public static void
printLarger(
int
b,
int
c) {
if
(b >= c) { System.out.println(b); }
else
{ System.out.println(c); }
}
/**
Print larger of
b
and
c
and larger of
b
and
c*c */
public static void
printLarger2(
int
b,
int
c) {
printLarger(b, c);
printLarger(b, c * c);
}
}
Figure 2.10:
Class
X
with two
static
procedures
Search WWH ::
Custom Search