AP CSA Unit 1 Day 1: Declaring Variables
Share
Declaring and Initializing Variables
Section 1.2 — Variables and Data Types
Key Concept
In Java, every variable must be declared with a specific data type before it can be used. Primitive types like int and double store values directly in memory. A critical distinction is that integer division in Java truncates the decimal portion entirely — 17 / 5 produces 3, not 3.4. The resulting type of an arithmetic expression is determined by the operands before any assignment occurs, so storing an integer division result in a double variable gives 3.0, not 3.4.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (B) 3.0 3
Trace each line:
Line 3: a / b is 17 / 5. Since both are int, this is integer division: result is 3 (truncated). Assigning to a double stores 3.0.
Line 4: (double) b promotes b to 5.0. Now 17 / 5.0 = 3.4. Then (int)(3.4) truncates to 3.
Output: 3.0 3
Why Not the Others?
(A) 3.4 would require a / b to perform floating-point division, but both operands are int. Integer division happens first, producing 3, which is then stored as 3.0.
(C) This assumes both divisions produce 3.4 and that (int)(3.4) rounds up to 4. Casting to int always truncates.
(D) The second value cannot be 4. (int)(3.4) truncates to 3, not 4. Java casting never rounds.
Common Mistake
Students often think assigning an integer division result to a double variable preserves the decimal. It does not. 17 / 5 produces 3 as an int first, then stores it as 3.0.
AP Exam Tip
When you see division, immediately check: are both operands int? If yes, the result is int regardless of what variable type stores it.