Skip to the content.

Casting and Range of Variables

AP CSA Unit 1.5 — Casting and Range of Variables (2025)

Scope: Java casting between int and double, integer division, modulus, and range/overflow behavior of int.
Goal: Predict results, spot overflow, and place casts correctly to control evaluation.

Introduction

What do you expect the output of this program to be??

int a = 5, b = 2;
System.out.println(a / b);
System.out.println((double)a / b);
System.out.println((int)3.9);
System.out.println((int)(3.9 + 0.5));
2
2.5
3
4

Learning goals

  • Use (int) and (double) correctly.
  • Explain truncation vs rounding.
  • Predict results of mixed int/double expressions.
  • Identify overflow with Integer.MAX_VALUE / Integer.MIN_VALUE.
  • Apply % and integer division rules.

Quick reference

Casting

  • Widening (automatic): int → double (no loss).
  • Narrowing (explicit): double → int with truncation toward 0.

Integer division

  • If both operands are int, result is int with truncation.
  • % returns the remainder.

Ranges

  • int: from -2^31 to 2^31 - 1-2147483648 to 2147483647.
  • double: ~15 digits of precision, IEEE 754.

Rounding to nearest int (per AP CSA CED)

  • Non‑negative x: (int)(x + 0.5)
  • Negative x: (int)(x - 0.5)

Casting in Java

public class CastDemo {
    public static void main(String[] args) {
        int a = 7, b = 2;
        System.out.println(a / b);          // 3  (int division)
        System.out.println((double)a / b);  // 3.5 (promoted to double before divide)

        double d = 5.9;
        int t = (int) d;                    // 5  (truncate toward 0)
        System.out.println(t);

        // Rounding to nearest int (per CED):
        int rPos = (int)(d + 0.5);          // 6  (non-negative rounding)
        double n = -5.9;
        int rNeg = (int)(n - 0.5);          // -6 (negative rounding)
        System.out.println(rPos + " " + rNeg);
    }
}

Integer division and %

int x = 17, y = 5; System.out.println(x / y); // 3 System.out.println(x % y); // 2

Properties: x == (x / y) * y + (x % y) when y != 0.

Range and overflow in Java int

int max = Integer.MAX_VALUE;  //  2147483647
int min = Integer.MIN_VALUE;  // -2147483648

System.out.println(max + 1);  // overflow → -2147483648
System.out.println(min - 1);  // overflow →  2147483647
-2147483648
2147483647

Overflow wraps around within the 32‑bit signed range.

Python helper: simulate Java 32‑bit int

The following Python utilities mimic Java’s 32‑bit signed int arithmetic so you can experiment inside this notebook.


# Utilities to simulate Java 32-bit signed int in Python
INT_MIN = -2**31
INT_MAX =  2**31 - 1
MASK32  =  0xFFFFFFFF

def to_int32(x: int) -> int:
    x &= MASK32
    # convert to signed
    return x if x <= INT_MAX else x - (1 << 32)

def add_int32(a: int, b: int) -> int:
    return to_int32(a + b)

def sub_int32(a: int, b: int) -> int:
    return to_int32(a - b)

def mul_int32(a: int, b: int) -> int:
    return to_int32(a * b)

def div_int32(a: int, b: int) -> int:
    # Java int division truncates toward zero
    if b == 0:
        raise ZeroDivisionError("division by zero")
    q = int(a / b)  # Python truncates toward zero for int()
    return to_int32(q)

def mod_int32(a: int, b: int) -> int:
    # Java remainder has same sign as dividend (a)
    if b == 0:
        raise ZeroDivisionError("mod by zero")
    q = div_int32(a, b)
    r = to_int32(a - q * b)
    return r

# Demo
print("INT_MIN, INT_MAX:", INT_MIN, INT_MAX)
print("Overflow examples:")
print("MAX+1 =", add_int32(INT_MAX, 1))
print("MIN-1 =", sub_int32(INT_MIN, 1))
print("(-7)/2  =", div_int32(-7, 2), "  (-7)%2 =", mod_int32(-7, 2))
print("(7)/-2  =", div_int32(7, -2), "  (7)%-2 =", mod_int32(7, -2))

INT_MIN, INT_MAX: -2147483648 2147483647
Overflow examples:
MAX+1 = -2147483648
MIN-1 = 2147483647
(-7)/2  = -3   (-7)%2 = -1
(7)/-2  = -3   (7)%-2 = 1

Truncation vs rounding (runnable demo)

In Java, (int) 5.95 because casting truncates toward 0.
The CED rounding technique: (int)(x + 0.5) for non‑negative, (int)(x - 0.5) for negative.


def java_truncate(x: float) -> int:
    # Casting double->int truncates toward 0
    return int(x)  # Python int() also truncates toward 0

def ced_round(x: float) -> int:
    if x >= 0:
        return int(x + 0.5)
    else:
        return int(x - 0.5)

tests = [5.1, 5.5, 5.9, -5.1, -5.5, -5.9, 0.49, -0.49]
for v in tests:
    print(f"x={v:5}  truncate={java_truncate(v):3}  ced_round={ced_round(v):3}")

x=  5.1  truncate=  5  ced_round=  5
x=  5.5  truncate=  5  ced_round=  6
x=  5.9  truncate=  5  ced_round=  6
x= -5.1  truncate= -5  ced_round= -5
x= -5.5  truncate= -5  ced_round= -6
x= -5.9  truncate= -5  ced_round= -6
x= 0.49  truncate=  0  ced_round=  0
x=-0.49  truncate=  0  ced_round=  0

Promotion rules in mixed expressions

  • If either operand is double, the other is promoted to double before the operation.
  • If both are int, integer arithmetic is used.
int a = 3, b = 2;
double x = a / b;          // 1.0   (int division then widened)
double y = (double)a / b;  // 1.5   (promoted before divide)

Practice: predict the output (Java)

Write your answers, then check against the key below.

Q1

int a = 10, b = 4;
System.out.println(a / b);
System.out.println(a % b);
System.out.println((double)(a / b));
System.out.println((double)a / b);
2
2
2.0
2.5

Q2

double d = -2.6;
System.out.println((int)d);
System.out.println((int)(d - 0.5));
System.out.println((int)(-d + 0.5));
-2
-3
3

Q3

int x = Integer.MAX_VALUE;
int y = x + 2;
System.out.println(x);
System.out.println(y);
2147483647
-2147483647

Answer key

Q1

2
2
2.0
2.5

Q2

-2
-3
3

Q3

2147483647
-2147483647   // wraps: MAX_VALUE + 2

Optional: use Python helpers to reason about Q1

The following Python mimics the Java behavior for integer parts.


# Q1 reasoning
a, b = 10, 4
print("a / b   =", int(a / b))   # integer division result
print("a % b   =", a - int(a / b) * b)
print("(double)(a / b) =", float(int(a / b)))
print("(double)a / b   =", a / b)  # Python uses float division here by default
a / b   = 2
a % b   = 2
(double)(a / b) = 2.0
(double)a / b   = 2.5

FRQ-style tasks

FRQ 1. Average with correct casting
Write a method avgInt that takes two int values and returns their average as a double, preserving the .5 if present.

public static double avgInt(int a, int b) {
    return (a + b) / 2.0;
}

System.out.println(avgInt(6, 7));
6.5

FRQ 2. Percentage
Given int correct and int total, compute the percentage as a double from 0.0 to 100.0 without losing fractional precision.

public static double percent(int correct, int total) {
    return (correct * 100.0) / total;
}

System.out.println(percent(45, 51));
88.23529411764706

FRQ 3. Safe remainder
Implement safeMod(int a, int b) that returns a % b, but if b == 0, it should return 0 instead of throwing.

public static int safeMod(int a, int b) {
    if (b == 0) {
        return 0;
    }
    return a % b;
}

System.out.println(safeMod(7, 3));
1

Suggested solutions (Java)

// FRQ 1
public static double avgInt(int a, int b) {
    return ((double)a + b) / 2.0;
}

// FRQ 2
public static double percent(int correct, int total) {
    if (total == 0) return 0.0;
    return 100.0 * ((double) correct) / total;
}

// FRQ 3
public static int safeMod(int a, int b) {
    if (b == 0) return 0;
    return a % b;
}

Java Casting MCQ’s

Here are 5 multiple-choice questions on Java casting:

Question 1: What is the output of the following code? A) 7.9
B) 8
**C) 7 ** D) 8.0
E) Compile error

double x = 7.9;
int y = (int) x;
System.out.println(y);
7

Question 2: Which of the following statements will compile without error? A) int c = a + b;
B) int c = (int)(a + b);
C) int c = a + (int)b;
D) Both B and C E) All of the above

int a = 10;
double b = 5.5;

Question 3: What is the result of the following code? A) 4.5
B) 4
C) 5
D) 4.0
E) Compile error

int num = 9 / 2;
System.out.println(num);
4

Question 4: Given the following code, what is printed? A) 15
B) 16 C) 15.5
D) 16.0
E) 15.7

double d = 15.7;
int i = (int)(d + 0.5);
System.out.println(i);
16

Question 5: Which statement about casting is TRUE? A) Casting from int to double requires explicit casting
B) Casting from double to int requires explicit casting
C) Casting from int to double may result in loss of data
D) Casting is never necessary in Java
E) Casting from double to int always rounds to the nearest integer

Homework Submission

  • MCQ answers (on the google form)
  • Entire notebook with all code cells EXECUTED and VISIBLE on your GitHub Pages (ex. https://yourgithubusername.github.io/)

Form link