Java Reference
In-Depth Information
Infix, Prefix, and Postfix Notation
When we write numeric expressions in a Java program, we typically put numeric
operators like + and * between the two operands, as in the following:
3.5 + 8.2
9.1 * 12.7
7.8 * (2.3 + 2.5)
Putting the operator between the operands is a convention known as infix notation.
A second convention is to put the operator in front of the two operands, as in the fol-
lowing examples:
+ 3.5 8.2
* 9.1 12.7
* 7.8 + 2.3 2.5
Putting the operator in front of the operands is a convention known as prefix nota-
tion. Prefix notation looks odd for symbols like + and * , but it resembles mathemati-
cal function notation, in which the name of the function goes first. For example, if we
were calling methods instead of using operators, we would write
plus(3.5, 8.2)
times(9.1, 12.7)
times(7.8, plus(2.3, 2.5))
There is also a third convention, in which the operator appears after the two
operands, as in the following examples:
3.5 8.2 +
9.1 12.7 *
7.8 2.3 2.5 + *
This convention is known as postfix notation. It is also sometimes referred to as
reverse Polish notation, or RPN. For many years Hewlett-Packard has sold scientific
calculators that use RPN rather than normal infix notation.
We are so used to infix notation that it takes a while to get used to the other two
conventions. One of the interesting facts you will discover if you take the time to
learn the prefix and postfix conventions is that infix is the only notation that requires
parentheses. The other two notations are unambiguous.
Table 12.1 summarizes the three notations.
Evaluating Prefix Expressions
Of the three standard notations, prefix notation is most easily implemented with
recursion. In this section we will write a method that reads a prefix expression
 
Search WWH ::




Custom Search