AP Computer Science A · Unit 1: Using Objects & Methods
1.5 Casting and Ranges of Variables
What is casting?
Casting explicitly converts a value from one data type to another. Widening (int → double) happens automatically and loses no data. Narrowing (double → int) requires an explicit cast like `(int) x` and can lose information, since Java simply truncates (drops) the decimal part rather than rounding.
Integer division vs. casting
Dividing two ints performs integer division, truncating any remainder (7/2 = 3). To get a decimal result, cast at least one operand to double before dividing, e.g., `(double) 7 / 2` = 3.5. Casting the whole expression after division won't help — the truncation already happened.
Ranges of variables
Primitive types have fixed storage sizes and value ranges. An int holds whole numbers roughly ±2.1 billion (32-bit). A double stores decimal values with much greater range and precision. Assigning a value outside a type's range, or improperly narrowing, causes overflow or data loss.
Key terms
- Casting
- Explicitly converting a value from one data type to another, e.g., (int) 5.7.
- Widening cast
- Automatic conversion to a larger type (e.g., int to double) with no data loss.
- Narrowing cast
- Explicit conversion to a smaller type (e.g., double to int) that can lose data through truncation.
- Integer division
- Division of two ints that truncates any decimal remainder, e.g., 7/2 = 3.
- How to force decimal division
- Cast at least one operand to double before dividing, e.g., (double) a / b.
Try an AP-style question
What is (int) 3.99?
- 4
- 3.99
- 3.0
- 3
Show the answer
D. Casting truncates.
Practice 8 AP-style questions with instant explanations, flashcards and spaced review.
Study 1.5 free in APrep