Page 111 - Introduction to Programming with Java: A Problem Solving Approach
P. 111

                3.16 Expression Evaluation and Operator Precedence 77
 1. grouping with parentheses: (<expression>)
2. unary operators: +x
-x
(<type>) x
3. multiplication and division operators: x* y
x/ y
x% y
4. addition and subtraction operators: x+y
x-y
Figure 3.7 Abbreviated operator precedence table (see Appendix 2 for the complete table)
Operator groups at the top of the table have higher precedence than operator groups at the bottom of the table. All operators within a particular group have equal precedence, and they evaluate left to right.
The operators in the second-from-the-top group are unary operators. A unary operator is an operator that Apago PDF Enhancer
applies to just one operand. The unary + operator is cosmetic; it does nothing. The unary - operator (negation) reverses the sign of its operand. For example, if the variable x contains a 6, then -x evaluates to a negative 6. The (<type>) operator represents the cast operators. We’ll get to cast operators later in this chapter.
Average Bowling Score Example Revisited
Let’s return to the average bowling score example and apply what you’ve learned about operator precedence. Does the following statement correctly calculate the average bowling score for three bowling games?
bowlingAverage = game1 + game2 + game3 / 3;
No. The operator precedence table says that the / operator has higher priority than the + operator, so divi- sion is performed first. After the JVM divides game3 by 3, the JVM adds game1 and game2. The correct way to calculate the average is to add the three game scores first and then divide the sum by 3. In other words, you need to force the + operators to execute first. The solution is to use parentheses like this:
bowlingAverage = (game1 + game2 + game3) / 3;
Expression Evaluation Practice
Let’s do some expression evaluation practice problems to ensure that you really under- stand this operator precedence material. Given these initializations:
int a = 5, b = 2;
   double c = 3.0;
Hand calcula- tion helps your understanding.











































































   109   110   111   112   113