1.05 Casting and Range of Variables
Convert between int and double with casts, predict integer division and truncation, round with (int)(x + 0.5), and recognize integer overflow.
1. Reference Guide
| Term | Definition / Example | College Board Requirement |
|---|---|---|
| Casting | Writing a type in parentheses to convert a value: (int) 5.9, (double) 7 |
Unit 1, Topic 1.5, p. 36 |
| Widening | int to double happens automatically, with no lost data: double y = 5; stores 5.0 |
Unit 1, Topic 1.5, p. 36 |
| Narrowing | double to int needs a cast, and the decimal part is dropped: (int) 5.9 is 5 |
Unit 1, Topic 1.5, p. 36 |
| Truncation | Dropping the decimal part, toward zero: (int) -5.9 is -5 |
Unit 1, Topic 1.5, p. 36 |
| Rounding | Add 0.5 before the cast for positives, subtract 0.5 for negatives: (int) (5.5 + 0.5) is 6 |
Unit 1, Topic 1.5, p. 36 |
Integer.MAX_VALUE / MIN_VALUE |
The largest and smallest int: 2147483647 and -2147483648 |
Unit 1, Topic 1.5, p. 37 |
| Integer overflow | A result outside the int range wraps around: Integer.MAX_VALUE + 1 is -2147483648 |
Unit 1, Topic 1.5, p. 37 |
- A cast applies only to the value right after it, so
(double) (7 / 2)is3.0but(double) 7 / 2is3.5 - Overflow does not crash and gives no error. The program keeps running with the wrong number
Type Casting Rules
| Direction | Name | Behavior | Example |
|---|---|---|---|
int to double |
Widening (automatic) | No loss of data | int x = 5; double y = x; gives 5.0 |
double to int |
Narrowing (needs a cast) | Truncates toward zero | double d = 5.9; int x = (int) d; gives 5 |
Integer Division vs Floating-Point Division
| Situation | Result | Example |
|---|---|---|
Both operands int |
int, decimals dropped |
7 / 2 is 3 |
At least one double |
double |
7.0 / 2 is 3.5 |
| Cast before dividing | The cast happens first | (double) 7 / 2 is 3.5 |
| Cast after dividing | Too late, the decimal is already gone | (double) (7 / 2) is 3.0 |
Truncation vs Rounding
| Operation | Behavior | Example |
|---|---|---|
(int) x |
Truncate toward zero | (int) 5.9 is 5, (int) -5.9 is -5 |
(int) (x + 0.5) |
Round a non-negative number | (int) (5.4 + 0.5) is 5, (int) (5.5 + 0.5) is 6 |
(int) (x - 0.5) |
Round a negative number | (int) (-5.4 - 0.5) is -5, (int) (-5.5 - 0.5) is -6 |
Integer Range
| Type | Minimum | Maximum | Notes |
|---|---|---|---|
int |
-2147483648 |
2147483647 |
32 bits, -2^31 to 2^31 - 1 |
double |
very large negative | very large positive | about 15 significant digits |
Predicting a Mixed-Type Expression
- Both values are
int→ integer division, decimals dropped - A cast sits right before a value → that value converts first, then the math happens
- A cast sits before parentheses → the math inside happens first, then the result converts
- An
intresult would pass 2147483647 → it wraps to a negative number
College Board Requirements
AP CSA Unit 1, Topic 1.5 Casting and Range of Variables. Quoted from the course and exam description (College Board, 2025, pp. 36-37):
- “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.”
- “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.”
The Java language specification gives the rule behind truncation: a floating-point value converted to an integer “is rounded to an integer value V using the round toward zero rounding policy” (Gosling et al., 2023, section 5.1.3). That is why (int) 5.9 is 5, and why rounding needs the + 0.5 step.
Reference: College Board, AP Computer Science A Course and Exam Description (2025), Unit 1, Topic 1.5, pp. 36–37.
2. Real-Life Application
The Video That Ran Out of Numbers
In December 2014, YouTube announced that one music video had been watched more than 2,147,483,647 times. That number is Integer.MAX_VALUE. Its view counter was a 32-bit integer, and one more view would have wrapped the count to a negative number. YouTube switched the counter to a 64-bit integer before that happened. Everyone guess: what would the counter have shown after view number 2,147,483,648?
| Real Case | What Happened | Java Idea in This Lesson |
|---|---|---|
| YouTube view counter (2014) | A 32-bit counter reached its limit, so YouTube made it 64 bits wide | Integer.MAX_VALUE + 1 wraps to -2147483648 |
| Boeing 787 power units (2015) | The U.S. Federal Aviation Administration ordered 787 operators to restart the planes’ generator control units at least every 248 days, because a 32-bit counter of hundredths of a second would overflow and shut the generators down | 2^31 hundredths of a second is about 248 days. Overflow gives no error, it just gives a wrong value |
| Grade averages | int points divided by int assignments drops the decimal |
(double) total / count keeps it |
| Star ratings | 4.6 stars shown as 4 instead of 5 | (int) 4.6 truncates; (int) (4.6 + 0.5) rounds |
The takeaway: know the range of your type and decide when the conversion happens. Neither overflow nor truncation gives an error message.
3. Tech Talk
Learning Objective: Predict the result of casting between int and double, explain integer division and truncation, round with a cast, and recognize integer overflow.
Success Criteria: You can trace a mixed-type expression, place a cast so the division keeps its decimal, round positive and negative numbers, and say when an int will overflow.
Java checks types strictly. When types mix, the result depends on what each value is at the moment the operator runs.
System.out.println(7 / 2); // 3 (int / int)
System.out.println((double) 7 / 2); // 3.5 (7 becomes 7.0 first)
System.out.println((double) (7 / 2)); // 3.0 (7 / 2 is already 3)
System.out.println((int) 3.9); // 3 (truncated, not rounded)
System.out.println((int) (3.9 + 0.5)); // 4 (rounded)
Overflow is silent:
int max = Integer.MAX_VALUE; // 2147483647
System.out.println(max + 1); // -2147483648
Code Examples
A. Where the cast goes. The DivisionAndCasting class shows integer division, cast placement, truncation, and rounding
Students often put the cast in the wrong place:
double avg = (double) (sum / count); // too late: sum / count already dropped the decimal
double avg = (double) sum / count; // sum becomes a double first, so the decimal stays
Terminology:
Narrowing a double to an int always truncates toward zero. To round, shift the value by 0.5 first, then cast.
Code Runner Challenge
Predict each line, run it, then move one cast and predict again
View IPYNB Source
// CODE_RUNNER: Predict each line, run it, then move one cast and predict again
public class DivisionAndCasting {
public static void main(String[] args) {
int sum = 10, count = 3;
System.out.println(sum / count); // 3: int / int
System.out.println(sum % count); // 1: the remainder
System.out.println((double) sum / count); // 3.3333333333333335: cast first
System.out.println((double) (sum / count)); // 3.0: cast after the division
double d = 5.7;
System.out.println((int) d); // 5: truncated
System.out.println((int) (d + 0.5)); // 6: rounded
System.out.println((int) (-d - 0.5)); // -6: rounding a negative
}
}
DivisionAndCasting.main(null);
B. Range and overflow. The OverflowDemo class shows what happens past the edges of int
An int has 32 bits. Going one past either end wraps around to the other end, with no error.
Integer.MAX_VALUE + 1 // -2147483648
Integer.MIN_VALUE - 1 // 2147483647
Terminology:
Integer overflow: the true answer does not fit in an int, so Java keeps a value that does fit, which is usually far from the true answer.
Code Runner Challenge
Predict the two wrap-around lines, run it, then change the coin values
View IPYNB Source
// CODE_RUNNER: Predict the two wrap-around lines, run it, then change the coin values
public class OverflowDemo {
public static void main(String[] args) {
int max = Integer.MAX_VALUE;
int min = Integer.MIN_VALUE;
System.out.println("Max int: " + max);
System.out.println("Min int: " + min);
System.out.println("Max + 1: " + (max + 1)); // wraps to the minimum
System.out.println("Min - 1: " + (min - 1)); // wraps to the maximum
// A game wallet that is almost full
int coins = 2000000000;
coins = coins + 500000000;
System.out.println("Coins: " + coins); // negative: overflow
}
}
OverflowDemo.main(null);
Hacks & Practice Tasks
Lesson: CSA 1.5 Casting and Range of Variables
MCQ 1.5: <paste the copied result line, such as 3/4 | answers: B,C,A,D>
Popcorn: five casting predictions, Q6 prints 3.5 with a cast (yes/no); predictions right = <n>/5
Homework Hack 1: all three average and percent checks print true (yes/no)
Homework Hack 2: all four rounding checks print true (yes/no); the negative rule = <one line>
Homework Hack 3: all four overflow checks print true (yes/no); why not test current + added = <one line>
Submission Safety Rules (Read First)
- One class per cell, ending with
ClassName.main(null);. - Label the homework hacks 1 through 3.
- Write your Popcorn predictions before you run it.
- Run each Java cell and leave the output showing.
- Include your MCQ score.
- Use
##headings or smaller.
Popcorn Hack (In-Class)
2-minute challenge: predict five casting results, then fix one average.
- Read the five
Qlines in the cell. Do not run it yet - Type your prediction for each line into the Popcorn checker under the runner
- Fill in
Q6so it prints3.5: dividepointsbygameswith a cast, not by typing3.5 - Run the cell. Check your predictions against the output. When every check passes, copy the checker’s line into your submission notes
Leave Q1 to Q5 as they are.
Code Runner Challenge
Predict Q1 to Q5 in the checker, fill in Q6, then run it
View IPYNB Source
// CODE_RUNNER: Predict Q1 to Q5 in the checker, fill in Q6, then run it
// Practice #1 - Try it yourself first!
public class CastingPredictions {
public static void main(String[] args) {
int a = 10, b = 4;
double d = 7.8;
int x = Integer.MAX_VALUE;
System.out.println("Q1: " + (a / b));
System.out.println("Q2: " + ((double) a / b));
System.out.println("Q3: " + ((int) d));
System.out.println("Q4: " + ((int) (d + 0.5)));
System.out.println("Q5: " + (x + 1));
int points = 7, games = 2;
double average = 0; // TODO: divide points by games so the decimal is kept
System.out.println("Q6: " + average);
}
}
CastingPredictions.main(null);
Before you press Run, predict what each line prints after "Qn: ".
4. MCQ Check
4 questions, one at a time. Answer, check, then go to the next one. At the end, copy the score line into your submission notes.
5. Homework Hack
Task: Do all three hacks. Each starter compiles and runs, so you can run the initial version and compare its incorrect output with the expected output. Change only what the TODO asks for, and keep going until every check prints true.
Solution Skeleton:
Hack 1: Keep the Decimal (5 minutes)
Casting before dividing. averageAsDouble and percentScore both lose their decimals to integer division. Move or add a cast so each check prints true. percentScore should still return 0.0 when total is 0.
Code Runner Challenge
Fix the two methods with casts until all three checks print true.
View IPYNB Source
// CODE_RUNNER: Fix the two methods with casts until all three checks print true.
public class AverageHack {
// TODO: cast so the average keeps its decimal part
public static double averageAsDouble(int a, int b) {
return (a + b) / 2;
}
// TODO: cast so 7 out of 10 gives 70.0, not 0.0
public static double percentScore(int correct, int total) {
if (total == 0) {
return 0.0; // avoid dividing by zero
}
return correct / total * 100;
}
public static void main(String[] args) {
System.out.println("Average of 5 and 10: " + averageAsDouble(5, 10));
System.out.println("7 out of 10: " + percentScore(7, 10) + "%");
System.out.println(averageAsDouble(5, 10) == 7.5);
System.out.println(percentScore(7, 10) == 70.0);
System.out.println(percentScore(0, 0) == 0.0);
}
}
AverageHack.main(null);
Hack 2: Round Both Ways (5 minutes)
Truncation vs rounding. nearestInteger only truncates right now. Use the rounding rules from the Reference Guide so positive and negative numbers both round to the nearest whole number.
Code Runner Challenge
Round positives and negatives correctly so all four checks print true.
View IPYNB Source
// CODE_RUNNER: Round positives and negatives correctly so all four checks print true.
public class RoundingHack {
// TODO: add 0.5 for non-negative values, subtract 0.5 for negative values, then cast
public static int nearestInteger(double value) {
return (int) value;
}
public static void main(String[] args) {
System.out.println("Round 5.5: " + nearestInteger(5.5));
System.out.println("Round -5.5: " + nearestInteger(-5.5));
System.out.println(nearestInteger(5.4) == 5);
System.out.println(nearestInteger(5.5) == 6);
System.out.println(nearestInteger(-5.4) == -5);
System.out.println(nearestInteger(-5.5) == -6);
}
}
RoundingHack.main(null);
Hack 3: Catch Overflow Before It Happens (10 minutes)
Combined. The wallet in Example B went negative. Write willOverflow so it returns true when current + added would pass Integer.MAX_VALUE. Assume added is not negative. Do not compute current + added to check it: that sum may already have wrapped around. Compare current with Integer.MAX_VALUE - added instead.
Code Runner Challenge
Write willOverflow without computing current + added, so all four checks print true.
View IPYNB Source
// CODE_RUNNER: Write willOverflow without computing current + added, so all four checks print true.
public class OverflowGuard {
// TODO: return true when current + added would be larger than Integer.MAX_VALUE
public static boolean willOverflow(int current, int added) {
return false;
}
public static void main(String[] args) {
int coins = 2000000000;
int reward = 500000000;
if (willOverflow(coins, reward)) {
System.out.println("Wallet full: reward not added");
} else {
coins += reward;
System.out.println("Coins: " + coins);
}
System.out.println(willOverflow(2000000000, 500000000) == true);
System.out.println(willOverflow(100, 50) == false);
System.out.println(willOverflow(Integer.MAX_VALUE, 1) == true);
System.out.println(willOverflow(Integer.MAX_VALUE - 1, 1) == false);
}
}
OverflowGuard.main(null);
Grading Plan (1 Point Total)
| Part | Points | What earns the points |
|---|---|---|
| Popcorn | 0.2 | Five predictions written before running, Q1 to Q5 unchanged, and Q6 prints 3.5 from a (double) cast. The Popcorn checker line is in the notes. |
| MCQ | 0.2 | 4 correct. 0.15 for 2 or 3, 0.1 if every question was answered. |
| Homework Hack 1 | 0.2 | Both methods cast before dividing, percentScore still guards total == 0, and all three checks print true. |
| Homework Hack 2 | 0.15 | nearestInteger rounds non-negative and negative values, and all four checks print true. |
| Homework Hack 3 | 0.25 | willOverflow compares against Integer.MAX_VALUE - added without computing the sum, and all four checks print true. |
| Total | 1.0 |
Quick Validation Checklist
- Each cell ends with
ClassName.main(null);and shows output. - Popcorn predictions written before running, and the checker line is in the notes.
- MCQ score in the notes.
- No
(double) (a / b)where the decimal must be kept. nearestInteger(5.5)is6andnearestInteger(-5.5)is-6.- Every homework check prints
true.
6. LxD Cycle Process
Empathize: Students make casting errors without seeing what is happening. Their code compiles but prints the wrong answer, because they do not expect integer division, truncation instead of rounding, or overflow. They treat a cast as a magic symbol rather than a conversion that happens at one specific moment.
Define:
- POV: CSA students need a clear rule for when a conversion happens, because a wrong cast gives a wrong answer with no error message.
- Learning Goal: Students will predict the results of casts between
intanddouble, explain integer division and truncation, round with a cast, and recognize overflow in a 32-bitint.
Ideate:
- HMW Question: How might we get students to think about the type of each value at the moment each operator runs?
- HMW Question: How might we make silent errors like overflow visible before they ship?
- Activity: Predict casting results, run them to check, then fix averages, rounding, and a wallet that overflows.
Prototype:
- A reference guide, runnable examples for cast placement and overflow, a prediction Popcorn Hack with a checker, an MCQ knowledge check, three scaffolded homework hacks with self-checking output, and a grading rubric.
- A trial run showed that introducing widening, narrowing, division, rounding, and overflow at once was too much, so the lesson goes from cast placement to rounding to overflow, and each one has its own hack.
- Excellence means predicting the exact output, including where the cast takes effect, rather than only producing working code.
Test:
- Ask peers in peer review to complete the practice without additional explanation.
- Observe whether peers write predictions before they press run, and whether they put the cast before or after the division.
- Compare your lesson with another that is posted.
- Use the findings to revise any instruction or rubric criterion that did not guide students clearly.
- On submission, collect evidence from runner output, MCQ results, AI grading and student explanations.
- After teaching, grading and analysis, come back and revise lesson to complete teaching cycle for continuous improvement.
7. References/Citations
College Board. (2025). AP Computer Science A course and exam description [Effective fall 2025]. https://apcentral.collegeboard.org/media/pdf/ap-computer-science-a-course-and-exam-description-effective-fall-2025.pdf
Federal Aviation Administration. (2015). Airworthiness directives; The Boeing Company airplanes (AD 2015-09-07).
Gosling, J., Joy, B., Steele, G., Bracha, G., Buckley, A., Smith, D., & Bierman, G. (2023). The Java® language specification (Java SE 21 ed., section 5.1.3, Narrowing primitive conversion). Oracle. https://docs.oracle.com/javase/specs/jls/se21/html/jls-5.html
Submit Assignment
Need to update a submission later? Open the submissions dashboard.