AP CSA Unit 1 Day 9: Mixed Type Arithmetic

Unit 1 Foundation (Cycle 1) Day 9 of 28 Foundation

Mixed-Type Arithmetic and Promotion

Section 1.5 — Casting and Ranges

Key Concept

The Math class provides essential static methods for the AP CSA exam. Math.abs(x) returns the absolute value, Math.pow(base, exp) returns a double result, and Math.sqrt(x) returns a double. A key detail: Math.pow(2, 3) returns 8.0, not 8, because it always returns double. For random numbers, Math.random() returns a double in the range [0.0, 1.0). To generate a random integer in a range, use the formula: (int)(Math.random() * range) + min.

Consider the following code segment.

int m = 7; double n = 2.0; int p = 3; System.out.println(m / p + " " + m / n);

What is printed as a result of executing the code segment?

Answer: (A) 2 3.5

Two divisions with different types:

m / p: 7 / 3 = 2. Both are int, so integer division truncates.

m / n: 7 / 2.0 = 3.5. Since n is double, m is promoted to 7.0 before division. The result is a double.

Output: 2 3.5

Why Not the Others?

(B) The first result is an int division, so it prints as 2, not 2.0. The result of int / int is always an int.

(C) Integer division does not produce decimals. 7 / 3 between two int values gives 2, not 2.33.

(D) 7 / 2.0 is floating-point division and produces 3.5, not 3.0. When one operand is double, the other is promoted and full division occurs.

Common Mistake

The rule is simple: if either operand is double, Java promotes the other to double and performs floating-point division. If both are int, integer division occurs. The type of the variable storing the result does not matter.

AP Exam Tip

Before dividing, check the types of both operands. int / int gives int. int / double or double / int gives double. This is the single most tested concept in Unit 1.

Review this topic: Section 1.5 — Casting and Ranges • Unit 1 Study Guide

More Practice

Back to blog

Leave a comment

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