Unit 1 Cycle 2 Day 2: Order of Operations with Mixed Types

Unit 1 Advanced (Cycle 2) Day 2 of 28 Advanced

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.

int x = 5; int y = 2; double r1 = x / y; double r2 = (double) x / y; double r3 = (double) (x / y); System.out.println(r1 + " " + r2 + " " + r3);

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.

Review this topic: Section 1.3 — Expressions and Assignment • Unit 1 Study Guide

More Practice

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.