AP CSA Unit 1 Day 24: Mixed Types Review

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

Mixed Types: int, double, and String

Section Mixed — Review: Types and Expressions

Key Concept

Scope determines where a variable can be accessed in Java code. Local variables are only visible within the method (or block) where they are declared. Instance variables are accessible throughout the class. If a local variable has the same name as an instance variable, the local variable takes precedence (shadowing) — use this.variableName to access the instance variable. Method parameters behave like local variables with initial values. The AP exam tests scope errors where code tries to access a variable outside its declared block.

Consider the following code segment.

int a = 11; int b = 4; double c = 1.0 * a / b; int d = a / b; String result = d + " R" + a % b; System.out.println(c + " | " + result);

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

Answer: (A) 2.75 | 2 R3

Two different division paths:

c: 1.0 * a / b evaluates left to right. 1.0 * 11 = 11.0 (promoted to double). Then 11.0 / 4 = 2.75.

d: a / b = 11 / 4 = 2 (integer division).

a % b: 11 % 4 = 3 (remainder).

result: 2 + " R" + 3 = "2 R3" (concatenation since " R" is a String).

Output: 2.75 | 2 R3

Why Not the Others?

(B) 1.0 * a / b first multiplies by 1.0, promoting to double. 11.0 / 4 = 2.75, not 2.0. The 1.0 * trick forces floating-point division.

(C) d is an int from 11 / 4 = 2. It does not produce 2.75 because both operands are int.

(D) Neither value matches. c is 2.75 (floating-point) and d is 2 (integer).

Common Mistake

Multiplying by 1.0 is a common technique to force floating-point division. 1.0 * a promotes a to double, so the subsequent division is floating-point. Without it, a / b would be integer division.

AP Exam Tip

The AP exam often tests multiple type behaviors in one question. Trace each expression independently, checking operand types at every step. The type of the leftmost operand in a chain often determines the type of the whole expression.

Review this topic: Section Mixed — Review: Types and Expressions • Unit 1 Study Guide

More Practice

Back to blog

Leave a comment

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