This chapter goes into more depth about relational and logical operators. You will have to use these concepts to write complex programs that other people can read and follow.
3. Numeric Data and Operators
3.2. Operator Precedence
The built-in precedence order for arithmetic operators is shown in Table 5.6.
Table 5.6 Precedence order of the arithmetic operators
Precedence Order | Operator | Operation |
---|---|---|
1 | () | Parentheses |
2 | * / % | Multiplication, Division, Modulus |
3 | + - | Addition, Subtraction |
Parenthesized expressions have highest precedence and are evaluated first. Next come the multiplication, division, and modulus operators, followed by addition and subtraction. When we have an unparenthesized expression that involves both multiplication and addition, the multiplication would be done first, even if it occurs to the right of the plus sign. Operators at the same level in the precedence hierarchy are evaluated from left to right. For example, consider the following expression:
9 + 6 - 3 * 6 / 2
In this case, the first operation to be applied will be the multiplication (*), followed by division (/), followed by addition (+), and then finally the subtraction (). We can use parentheses to clarify the order of evaluation. A parenthesized expression is evaluated outward from the innermost set of parentheses:
Step 1 | ((9+6) - ((3*6) / 2)) |
---|---|
Step 2 | ((9+6) - (18/2)) |
Step 3 | ((9+6) - 9) |
Step 4 | (15 - 9) |
Step 5 | 6 |
Parentheses can (and should) always be used to clarify the order of operations in an expression. For example, addition will be performed before multiplication in the following expression:
( a + b) * c
Another reason to use parentheses is that Java's precedence and promotion rules will sometimes lead to expressions that look fine but contain subtle errors. For example, consider the following expressions:
System. out. println (5/ 3/ 2.0); // 0.5
System. out. println (5/(3 / 2.0)); // 3.33
JAVA PROGRAMMING TIP Parenthesize! To avoid subtle bugs caused by Java's precedence and promotion rules, use parentheses to specify the order of evaluation in an expression.