1. 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)

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 =
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

2. LxD Cycle Process

Empathize: I noticed students make casting and type-conversion errors without understanding what is actually happening. Many write code that compiles but produces unexpected results because they do not understand integer division, truncation versus rounding, or overflow behavior. They see casting as a “magic symbol” rather than a conscious type conversion.

Define:

  • POV: CSA students need a clear, systematic understanding of casting and numeric ranges because incorrect type conversions lead to subtle bugs that produce wrong answers without any error messages.
  • Learning Goal: Students will predict the results of casting operations, understand why integer division produces different results than floating-point division, apply appropriate rounding techniques, and recognize overflow behavior in 32-bit integers.

Ideate:

  • HMW Question: How might we teach students to think explicitly about types and their ranges so they make intentional casting choices and predict results correctly?
  • Activity: Building a mental model of how Java handles type conversion by tracing through expressions step-by-step, predicting outcomes, then verifying with code.

Prototype & Test: I taught a trial run. Students struggled when too many concepts (widening, narrowing, division, overflow, rounding) were introduced at once. I restructured to focus first on casting basics, then division rules, then overflow and ranges.


3. 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)


4. 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 (5 minutes)

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:

  1. Casting - Explicitly converting from one type to another
  2. Integer Division - When both operands are int, the result is int with truncation
  3. 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:

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);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

5. Code Examples

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);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...
// 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)));
    }
}

6. Hacks & Practice Tasks

Prepare your submission IPYNB

  1. Create a new notebook in your portfolio homework area: _notebooks/homework.
  2. Add one markdown cell at the top with the frontmatter:
---
layout: post
title: CSA Unit 1.5 Casting and Range HW
categories: [Java, Casting-and-Range]
lesson_language: Java
lesson_topic: Casting-and-Range HW
lesson_part: interactive
lesson_type: lesson
permalink: /csa/unit_01/1_5_hw
author: yourGithubID
---
  1. Add code cells for Popcorn and Homework. Ensure all code runs and output is visible.
  2. Include a markdown cell before each code section explaining the concept.

Submission Safety Rules (Read First)

[IMPORTANT] To avoid grading errors, follow these rules exactly:

  • Include your predictions before running each code section
  • Execute all code cells and leave output visible
  • Show your work for hand-traced predictions
  • Test edge cases (especially for overflow)
  • Do not just copy code; explain what each line does
  • Label each question clearly

Popcorn Hack (In-Class)

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:

  1. averageAsDouble(int a, int b) - Calculate the average of two integers as a double, preserving decimal values
  2. percentScore(int correct, int total) - Calculate a percentage (0.0 to 100.0) from whole numbers
  3. 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
    }
}

Grading Plan (1 Point Total)

Classroom Rubric

  • 0.2 points: Popcorn completion Student made predictions for all five questions and verified them with working Java code. Output matches expected results.

  • 0.8 points: Homework completion

    • 0.25 averageAsDouble: Correctly uses casting to prevent integer division. Test cases verify it returns proper decimal average.
    • 0.25 percentScore: Correctly casts to double before multiplication or division. Handles division by zero edge case.
    • 0.25 nearestInteger: Implements rounding correctly for both positive and negative numbers using the CED technique.
    • 0.05 Edge cases: Includes and tests at least one edge case per method (zero division, negative values, boundary values).

Quick Validation Checklist

  • Present: All code cells executed with output visible
  • Present: Predictions written before code for Popcorn Hack
  • Present: Three working methods with correct casting
  • Present: Test cases that demonstrate understanding
  • Present: Comments explaining casting logic
  • Absent: Integer division where floating-point is needed
  • Test: averageAsDouble(5, 10) = 7.5
  • Test: percentScore(7, 10) = 70.0
  • Test: nearestInteger(5.5) = 6 and nearestInteger(-5.5) = -6

7. Lesson Revisions & Feedback Evidence

Feedback Received: During peer review, colleagues noted that students struggled when assignment operators, division, and overflow were all presented together. They wanted more scaffolding for each concept.

Revision Made: I separated casting fundamentals from complex mixed-type expressions. Now the lesson progresses: (1) casting basics, (2) integer division rules, (3) rounding techniques, then (4) overflow as the most complex topic. Each has its own example and explanation.

Additional Refinement: The original homework asked students to implement five different methods, which was overwhelming. I reduced it to three core methods that directly test casting understanding. This focuses practice on the essential skill without cognitive overload.

Compiler Note: Added explicit explanation of operator precedence and casting order, because students frequently wrote (double)(x / y) thinking it would preserve decimals, when they actually needed (double)x / y.


8. 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.

Submit Assignment

Your code will be saved as a Gist and reviewed automatically. You must be logged in to submit.

Need to update a submission later? Open the submissions dashboard.