Unit 1 Cycle 2 Day 2: Order of Operations with Mixed Types
Share
Order of Operations with Mixed Types
Section 1.3 — Expressions and Assignment
Key Concept
When Java evaluates an expression with mixed int and double operands, each operation is evaluated independently. In a / b + c / d, each division uses the types of its own operands. If a and b are both int, that sub-expression uses integer division regardless of other terms. The AP exam exploits this by placing mixed-type operations in long expressions where students assume the entire expression uses floating-point math because one variable is a double.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (B) 2.0 2.5 2.0
Three different division scenarios:
r1: 5 / 2 = 2 (int / int = int). Then stored as 2.0.
r2: (double) x = 5.0. Then 5.0 / 2 = 2.5 (double / int = double).
r3: Parentheses first: x / y = 5 / 2 = 2 (int division). Then (double) 2 = 2.0. The cast comes too late.
Why Not the Others?
(A) r1 and r3 both perform integer division before any promotion to double. The decimal information is already lost by the time the result is stored.
(C) r3 casts the result of integer division, not the operand. (double)(5/2) = (double)(2) = 2.0, not 2.5.
(D) r1 is 2.0 (int division) and r2 is 2.5 (cast before division). These are switched in this option.
Common Mistake
Casting the result is not the same as casting an operand. (double)(x / y) performs integer division first, then converts. (double) x / y promotes x first, forcing floating-point division.
AP Exam Tip
This three-way comparison is an AP exam classic. Remember: cast an operand BEFORE division to get a decimal result. Casting AFTER division only converts the already-truncated integer.