AP CSA Unit 1 Day 4: Operator Precedence
Share
Arithmetic Operator Precedence
Section 1.3 — Expressions and Assignment
Key Concept
Java follows strict arithmetic operator precedence rules. Multiplication (*), division (/), and modulo (%) are evaluated before addition (+) and subtraction (-). When operators have equal precedence, they are evaluated left to right. Parentheses always override the default order. A common AP exam trap involves mixing int and double in the same expression — if either operand is a double, the result is promoted to double.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (B) 13 15
Apply standard order of operations:
Line 1: Multiplication first: 3 * 4 = 12. Then left to right: 2 + 12 - 1 = 13.
Line 2: Parentheses first: (2 + 3) = 5 and (4 - 1) = 3. Then: 5 * 3 = 15.
Output: 13 15
Why Not the Others?
(A) 19 would come from evaluating left to right without precedence: (2 + 3) * 4 - 1 = 19. Java follows standard math precedence: multiply/divide before add/subtract.
(C) Neither value is 19. The first expression respects operator precedence, not left-to-right evaluation.
(D) The second value is 15, not 19. Parentheses force (2+3)=5 and (4-1)=3, giving 5*3=15.
Common Mistake
The most common error is evaluating 2 + 3 * 4 - 1 left to right as 5 * 4 - 1 = 19. Java uses standard math precedence: multiplication and division happen before addition and subtraction.
AP Exam Tip
On the AP exam, always apply PEMDAS: Parentheses first, then Multiplication/Division (left to right), then Addition/Subtraction (left to right). Modulo (%) has the same precedence as multiplication and division.