Opening the reading…
Opening the reading…
PROGRAMMING FUNDAMENTALS › JAVA FUNDAMENTALS
Start with the complete statement: Java does not treat every arithmetic operator as part of one strict left-to-right march. Operators have precedence, which determines which parts of the expression group together first. Division, multiplication, and remainder have higher precedence than subtraction and addition, so the first reducible part is 6 / 3, not 18 - 6.
int result = 18 - 6 / 3 * 2 + 5 % 3;The higher-precedence operations form two groups in this expression. The division and multiplication group becomes (6 / 3) * 2, while the remainder group is 5 % 3. Only after those groups are formed can Java apply the subtraction and addition around them.
Which operation should be reduced first in a left-to-right written trace of int result = 18 - 6 / 3 * 2 + 5 % 3;?
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
Division and multiplication have equal precedence, so Java uses left associativity to group 6 / 3 * 2 as (6 / 3) * 2. It does not group it as 6 / (3 * 2). The same rule applies to subtraction and addition after the higher-precedence groups are reduced: 18 - 4 + 2 becomes (18 - 4) + 2.
The complete implicit grouping is therefore ((18 - ((6 / 3) * 2)) + (5 % 3)). Precedence decides which different kinds of operators get grouped first. Left associativity decides the order within a group of operators that share the same precedence.
Parentheses can force a lower-precedence operation to group before the operations around it. In the original expression, 18 - 6 is separated by the higher-precedence operations. Adding parentheses makes it the first group, while keeping every literal and operator from the running expression.
int result = (18 - 6) / 3 * 2 + 5 % 3;The forced group evaluates to 12. Left associativity then makes 12 / 3 * 2 evaluate as (12 / 3) * 2, producing 8, while 5 % 3 produces 2. The final addition gives 10, so changing the grouping changes the stored value from 16 to 10.
Rewrite the original expression so that 18 - 6 is grouped first.
int result = 18 - 6 / 3 * 2 + 5 % 3;Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
You can verify the value assigned to result by reducing the original expression one operation at a time. First reduce the leftmost higher-precedence operation, then continue within its group, and only then reduce the lower-precedence operations.
18 - 6 / 3 * 2 + 5 % 3
18 - 2 * 2 + 5 % 3
18 - 4 + 5 % 3
18 - 4 + 2
14 + 2
16The final reduction is 16, so the assignment stores that value in result. The value is predictable because precedence determines the higher-precedence groups, left associativity determines the order of equal-precedence operations, and no parentheses override the original grouping.