Java Reference
In-Depth Information
default:
break
}
}
while
(!operatorStack.isEmpty())
{
topOperator = operatorStack.pop()
operandTwo = valueStack.pop()
operandOne = valueStack.pop()
result =
the result of the operation in
topOperator
and its operands
operandOne
and
operandTwo
valueStack.push(result)
}
return
valueStack.peek()
Question 8
Using the previous algorithm, evaluate each of the following infix expres-
sions. Assume that
a
= 2,
b
= 3,
c
= 4,
d
= 5, and
e
= 6.
a.
a
+
b
*
c
-
9
b.
(
a
+
e
)
/
(
b
-
d
)
c.
a
+
(
b
+
c
*
d
)
-
e
/
2
d.
e
-
b
*
c
^
a
+
d
5.22
When a program executes, a special location called the
program counter
references the current
instruction. The program counter might be part of an actual computer or, in the case of Java, part of
a virtual computer.
3
When a method is called, the program's run-time environment creates an object called an
activation
record
, or
frame
, for the method. The activation record shows the method's state during its execution. In
particular, the activation record contains the method's arguments, local variables, and a reference to the cur-
rent instruction—that is, a copy of the program counter. At the time the method is called, the activation
record is pushed onto a stack called the
program stack
or, in Java, the
Java stack
. Since one method can
call another, the program stack often contains more than one activation record. The record at the top of the
stack belongs to the method that is currently executing. The record just beneath the top record belongs to
the method that called the current method, and so on.
Figure 5-13 illustrates a program stack for a
main
method that calls
methodA
, which then
calls
methodB
. When
main
begins execution, its activation record is at the top of the program
stack (Figure 5-13a). When
main
calls
methodA
, a new record is pushed onto the stack. The pro-
gram counter is 50 at that time. Figure 5-13b shows the updated record for
main
and the new
record for
methodA
just as the method begins execution. When
methodA
calls
methodB
, the pro-
gram counter is 120. A new activation record is pushed onto the stack. Figure 5-13c shows the
unchanged record for
main
, the updated record for
methodA
, and the new record for
methodB
just as it begins execution.
3.
To maintain computer independence, Java runs on a virtual computer called the
Java Virtual Machine
(
JVM
).