1.05 Casting and Range of Variables
Convert between data types and understand the limits of primitive types.
- Reference Guide
- College Board Requirements
- Lesson Plan
- Tech Talk & Introduction
- Code Runner Challenge
- Code Examples
- Code Runner Challenge
- Hacks & Practice Tasks
- References
Reference Guide
Type Casting Rules
| Direction | Name | Behavior | Example |
|---|---|---|---|
| int to double | Widening (automatic) | No loss of data, automatic | int x = 5; double y = x; yields 5.0 |
| double to int | Narrowing (explicit) | Truncates toward zero, requires cast | double d = 5.9; int x = (int)d; yields 5 |
Integer Division vs Floating-Point Division
| Situation | Result | Why |
|---|---|---|
| Both operands int | int result, truncated | 7 / 2 = 3 (not 3.5) |
| At least one double | double result | 7.0 / 2 = 3.5 or (double)7 / 2 = 3.5 |
| Cast before operation | Determined by cast | (double)7 / 2 = 3.5 (promote first, then divide) |
Truncation vs Rounding
| Operation | Behavior | Example |
|---|---|---|
(int) x |
Truncate toward zero | (int) 5.9 = 5, (int) -5.9 = -5 |
(int)(x + 0.5) |
Round for non-negative | (int)(5.4 + 0.5) = 5, (int)(5.5 + 0.5) = 6 |
(int)(x - 0.5) |
Round for negative | (int)(-5.4 - 0.5) = -5, (int)(-5.5 - 0.5) = -6 |
Integer Ranges
| Type | Minimum | Maximum | Range |
|---|---|---|---|
int |
-2147483648 | 2147483647 | -2^31 to 2^31 - 1 |
double |
Very small (negative) | Very large (positive) | IEEE 754, about 15 digits precision |
Key Point: When an int exceeds its range, it wraps around (overflow). MAX_VALUE + 1 becomes MIN_VALUE.
Operator Precedence (Casting Context)
Run it, then change a value and predict the new output
// Integer Division & Type Casting Examples
public class DivisionAndCasting {
public static void main(String[] args) {
int a = 5, b = 2;
System.out.println("Integer division (5 / 2):");
System.out.println(a / b); // 2 (integer division)
System.out.println("\nWidening cast before divide:");
System.out.println((double)a / b); // 2.5 (cast to double)
System.out.println("\nTruncation toward zero:");
System.out.println((int)3.9); // 3 (truncation)
System.out.println("\nRounding technique:");
System.out.println((int)(3.9 + 0.5));// 4 (add 0.5 then truncate)
}
}
Code Runner Challenge
Run it, then change a value and predict the new output
View IPYNB Source
1. Parentheses ()
2. Cast (int), (double)
3. Arithmetic *, /, %
4. Arithmetic +, -
5. Assignment =
College Board Requirements
Topic 1.5, Casting and Range of Variables, is required content tested directly on the AP Computer Science A Exam. The College Board’s official course framework states:
“The casting operators (int) and (double) can be used to convert from a double value to an int value (or vice versa)… Casting a double value to an int value causes the digits to the right of the decimal point to be truncated.” (College Board, 2025, p. 36)
The framework also defines the overflow behavior demonstrated in Code Example C above:
“If an expression would evaluate to an int value outside of the allowed range, an integer overflow occurs. The result is an int value in the allowed range but not necessarily the value expected.” (College Board, 2025, p. 37)
Lesson Plan
Learning Objective: By the end of this lesson, you will be able to predict the results of casting operations between int and double, understand integer division and truncation, apply proper rounding techniques, and explain overflow behavior in 32-bit integers.
Success Criteria: You can trace through mixed-type expressions, place casts correctly to control evaluation order, predict truncation versus rounding results, and identify when integer overflow will occur.
Tech Talk & Introduction
Java is a strongly-typed language. That means every variable has a specific type, and when you mix types, Java has rules about what happens. Understanding these rules is crucial to writing correct code.
The Three Key Concepts:
- Casting - Explicitly converting from one type to another
- Integer Division - When both operands are int, the result is int with truncation
- Overflow - What happens when a number exceeds the range of its type
Why do we do this? Casting lets you control type conversions precisely. Understanding integer division prevents silent errors. Knowing overflow behavior helps you avoid wrapping issues in calculations.
This example demonstrates all three concepts:
Run it, then change a value and predict the new output
// A. Simple: Understanding Integer Division
public class IntegerDivisionDemo {
public static void main(String[] args) {
int a = 7, b = 2;
System.out.println("Both operands are int:");
System.out.println(a / b); // 3 (truncated, not 3.5)
System.out.println(a % b); // 1 (remainder)
System.out.println("\nCast one operand to double before operation:");
System.out.println((double)a / b); // 3.5 (division on doubles)
System.out.println(a / (double)b); // 3.5 (division on doubles)
}
}
Code Runner Challenge
Run it, then change a value and predict the new output
View IPYNB Source
// CODE_RUNNER: Run it, then change a value and predict the new output
// Integer Division & Type Casting Examples
public class DivisionAndCasting {
public static void main(String[] args) {
int a = 5, b = 2;
System.out.println("Integer division (5 / 2):");
System.out.println(a / b); // 2 (integer division)
System.out.println("\nWidening cast before divide:");
System.out.println((double)a / b); // 2.5 (cast to double)
System.out.println("\nTruncation toward zero:");
System.out.println((int)3.9); // 3 (truncation)
System.out.println("\nRounding technique:");
System.out.println((int)(3.9 + 0.5));// 4 (add 0.5 then truncate)
}
}
DivisionAndCasting.main(null);
Code Examples
Run it, then change a value and predict the new output
// B. Intermediate: Casting and Rounding
public class CastingAndRoundingDemo {
public static void main(String[] args) {
double d = 5.7;
System.out.println("Positive number:");
int truncated = (int)d;
System.out.println("Truncate 5.7: " + truncated); // 5
int rounded = (int)(d + 0.5);
System.out.println("Round 5.7: " + rounded); // 6
System.out.println("\nNegative number:");
double neg = -5.7;
int negTruncated = (int)neg;
System.out.println("Truncate -5.7: " + negTruncated); // -5
int negRounded = (int)(neg - 0.5);
System.out.println("Round -5.7: " + negRounded); // -6
}
}
Code Runner Challenge
Run it, then change a value and predict the new output
View IPYNB Source
// CODE_RUNNER: Run it, then change a value and predict the new output
// A. Simple: Understanding Integer Division
public class IntegerDivisionDemo {
public static void main(String[] args) {
int a = 7, b = 2;
System.out.println("Both operands are int:");
System.out.println(a / b); // 3 (truncated, not 3.5)
System.out.println(a % b); // 1 (remainder)
System.out.println("\nCast one operand to double before operation:");
System.out.println((double)a / b); // 3.5 (division on doubles)
System.out.println(a / (double)b); // 3.5 (division on doubles)
}
}
IntegerDivisionDemo.main(null);
// CODE_RUNNER: Run it, then change a value and predict the new output
// B. Intermediate: Casting and Rounding
public class CastingAndRoundingDemo {
public static void main(String[] args) {
double d = 5.7;
System.out.println("Positive number:");
int truncated = (int)d;
System.out.println("Truncate 5.7: " + truncated); // 5
int rounded = (int)(d + 0.5);
System.out.println("Round 5.7: " + rounded); // 6
System.out.println("\nNegative number:");
double neg = -5.7;
int negTruncated = (int)neg;
System.out.println("Truncate -5.7: " + negTruncated); // -5
int negRounded = (int)(neg - 0.5);
System.out.println("Round -5.7: " + negRounded); // -6
}
}
CastingAndRoundingDemo.main(null);
// CODE_RUNNER: Run it, then change a value and predict the new output
// C. Complex: Overflow and Mixed-Type Expressions
public class OverflowAndCastingDemo {
public static void main(String[] args) {
System.out.println("Understanding int range:");
int max = Integer.MAX_VALUE; // 2147483647
int min = Integer.MIN_VALUE; // -2147483648
System.out.println("Max int: " + max);
System.out.println("Min int: " + min);
System.out.println("\nOverflow wraps around:");
int overflow = max + 1;
System.out.println("Max + 1: " + overflow); // -2147483648 (wraps to MIN)
int underflow = min - 1;
System.out.println("Min - 1: " + underflow); // 2147483647 (wraps to MAX)
System.out.println("\nMixed-type calculations:");
int x = 10, y = 3;
System.out.println("Order matters with casting:");
double result1 = (double)(x / y); // 3.0 (int division first, then cast)
double result2 = (double)x / y; // 3.333... (cast first, then float division)
System.out.println("(double)(10/3) = " + result1); // 3.0
System.out.println("(double)10/3 = " + result2); // 3.333...
System.out.println("\nVerification: x == (x/y)*y + (x%y)");
System.out.println(x + " == (" + (x/y) + "*" + y + ") + " + (x%y));
System.out.println(x + " == " + ((x/y)*y + (x%y)));
}
}
Hacks & Practice Tasks
Popcorn Hack
5-minute challenge: Predict and verify casting results.
Task: For each of the following expressions, predict the output, then write Java code to verify your answer.
1. int a = 10, b = 4;
System.out.println(a / b);
2. int a = 10, b = 4;
System.out.println((double)a / b);
3. double d = 7.8;
System.out.println((int)d);
4. double d = 7.8;
System.out.println((int)(d + 0.5));
5. int x = Integer.MAX_VALUE;
System.out.println(x + 1);
Predictions Skeleton:
// CODE_RUNNER 1: Popcorn Hack - Casting and Division
// Run it, then change a value and predict the new output
public class CodeRunner1_PopcornHack {
public static void main(String[] args) {
// Question 1: Predict output
// int a = 10, b = 4; System.out.println(a / b);
// My prediction: ____
System.out.println("Q1: " + (10 / 4));
// Question 2: Predict output
// int a = 10, b = 4; System.out.println((double)a / b);
// My prediction: ____
System.out.println("Q2: " + ((double)10 / 4));
// Question 3: Predict output
// double d = 7.8; System.out.println((int)d);
// My prediction: ____
System.out.println("Q3: " + ((int)7.8));
// Question 4: Predict output
// double d = 7.8; System.out.println((int)(d + 0.5));
// My prediction: ____
System.out.println("Q4: " + ((int)(7.8 + 0.5)));
// Question 5: Predict output
// int x = Integer.MAX_VALUE; System.out.println(x + 1);
// My prediction: ____
int x = Integer.MAX_VALUE;
System.out.println("Q5: " + (x + 1));
}
}
Homework Hack
Task: Write three methods that demonstrate casting and type conversion:
- averageAsDouble(int a, int b) - Calculate the average of two integers as a double, preserving decimal values
- percentScore(int correct, int total) - Calculate a percentage (0.0 to 100.0) from whole numbers
- nearestInteger(double value) - Round a double to the nearest integer, handling both positive and negative numbers
Your solution must:
- Use proper casting to prevent integer division where floating-point is needed
- Include test cases that verify correct behavior
- Include comments explaining the casting logic
- Handle edge cases (division by zero, negative numbers)
Method Skeleton:
// CODE_RUNNER 2: Casting Practice
// Run it, then change a value and predict the new output
public class CodeRunner2_CastingPractice {
// Method 1: Calculate average of two integers as double
public static double averageAsDouble(int a, int b) {
// Cast one operand to double before division
// This prevents integer division result
return ((double)a + b) / 2.0;
}
// Method 2: Calculate percentage from score
public static double percentScore(int correct, int total) {
// Handle edge case where total is 0
// Cast to double to prevent integer division
if (total == 0) {
return 0.0;
}
return (100.0 * correct) / total;
}
// Method 3: Round to nearest integer
public static int nearestInteger(double value) {
// Use rounding technique based on sign
if (value >= 0) {
return (int)(value + 0.5);
} else {
return (int)(value - 0.5);
}
}
public static void main(String[] args) {
// Test averageAsDouble
System.out.println("Average of 5 and 10: " + averageAsDouble(5, 10)); // 7.5
System.out.println("Average of 3 and 4: " + averageAsDouble(3, 4)); // 3.5
// Test percentScore
System.out.println("80 out of 100: " + percentScore(80, 100) + "%"); // 80.0%
System.out.println("7 out of 10: " + percentScore(7, 10) + "%"); // 70.0%
System.out.println("0 out of 0: " + percentScore(0, 0) + "%"); // 0.0%
// Test nearestInteger
System.out.println("Round 5.4: " + nearestInteger(5.4)); // 5
System.out.println("Round 5.5: " + nearestInteger(5.5)); // 6
System.out.println("Round -5.4: " + nearestInteger(-5.4)); // -5
System.out.println("Round -5.5: " + nearestInteger(-5.5)); // -6
}
}
References
Reference List
College Board. (2025). AP Computer Science A: Course and exam description. https://apcentral.collegeboard.org/media/pdf/ap-computer-science-a-course-and-exam-description.pdf
Gosling, J., Joy, B., Steele, G., Bracha, G., & Buckley, A. (2023). The Java language specification: Java SE 21 edition (§5.1.3, Narrowing Primitive Conversion). Oracle America. https://docs.oracle.com/javase/specs/jls/se21/html/jls-5.html
Outside Academic Reference
The truncation rule the College Board describes is formally defined in the Java Language Specification’s rule for narrowing primitive conversions: a floating-point-to-integer conversion “is rounded to an integer value V using the round toward zero rounding policy” (Gosling et al., 2023, §5.1.3). This is the technical basis for why (int) 5.9 truncates to 5 instead of rounding to 6, and why the lesson’s (int)(x + 0.5) technique is needed to produce true rounding.