Page 110 - Introduction to Programming with Java: A Problem Solving Approach
P. 110
76 Chapter 3 Java Basics
Figure 3.6 also illustrates these additional examples:
8 / 12 ⇒ 0 8 % 12 ⇒ 8
Here is the corresponding grade school arithmetic notation:
0
12 8 -0
3.16 Expression Evaluation and Operator Precedence
In the above examples, the expressions were pretty basic—they each contained only one operator—so they were fairly easy to evaluate. Expressions are sometimes fairly complicated. In this section, we discuss how to evaluate those more complicated expressions.
Average Bowling Score Example
Suppose you’d like to calculate the average bowling score for three bowling games. Would this statement work?
bowlingAverage = game1 + game2 + game3 / 3;
The code looks reasonable. But it’s not good enough to rely on your sense of what looks reasonable. To be a good programmer, you need to be sure. The code you should be focusing on is the expression on the right side: game1 + game2 + game3 / 3. More specifically, you should be asking yourself, “Which operator executes first—the left addition operator or the division operator?” To answer that question, we turn to the operator precedence table.
Operator Precedence Table
The key to understanding complicated expressions is to understand the operator precedence shown in Figure 3.7. Please study Figure 3.7’s operator precedence table now.
The operator precedence table might need some clarification. The groups at the top have higher prece- dence than the groups at the bottom. That means that if one of the top operators appears in an expression along with one of the bottom operators, then the top operator executes first. For example, if * and + both appear in the same expression, then the * operator executes before the + operator (because the * operator’s group is higher in the table than the + operator’s group). If parentheses appear within an expression, then the items inside the parentheses execute before the items that are outside the parentheses (because parentheses are at the very top of the table).
If an expression has two or more operators in the same group (from Figure 3.7’s groups), then ap- ply the operators from left to right. In mathematics, that’s referred to as left-to-right associativity. In Java, that means that operators appearing at the left should be executed before operators appearing at the right. For example, since the * and / operator are in the same group, if * and / both appear in the same expression and / appears further to the left than * within that expression, division is performed before multiplication.
q
q
u
u
o
e
m
o
t
m
a
t
i
a
i
i
e
en
8
in
n
d
nt
t
r
r
e
de
e
r
r
Apago PDF Enhancer