APCSA 1.5 — Casting and Range of Variables

How Java converts between types, and what happens when values exceed a type’s limits.

1) What is Casting?

Casting is converting a value from one data type to another.

TypeSize (bits)Typical Range / ExampleNotes
byte8−128 to 127Smallest integer
short16−32,768 to 32,767Rarely used
int32≈ −2.1B to 2.1BDefault integer
long64Very large integersUse L suffix
float32e.g., 3.14fUse f suffix
double64e.g., 3.14159Default decimal
char16Single UTF-16 unitCharacters
booleantrue / falseLogical values

2) Widening Conversion (Automatic)

Moving a smaller type into a larger one is safe and automatic.

// int → double (automatic)
int score = 95;
double grade = score;   // 95.0 (no data lost)
Why it’s safe: The larger type can represent every value of the smaller type.

3) Narrowing Conversion (Manual)

Moving a larger type into a smaller one can lose data. You must cast explicitly.

// double → int (manual, truncates)
double pi = 3.14159;
int whole = (int) pi;   // 3 (fraction dropped, not rounded)
Heads-up: Casting from floating-point to integer truncates—no rounding.

4) Type Mismatch Errors

int x = 3.5;      // ❌ compile error: cannot convert double to int
int y = (int) 3.5; // ✅ y becomes 3

5) Range of Variables (Overflow & Underflow)

Each primitive type has a fixed range. Exceeding it wraps around.

byte b = 127;
b++;                     // wraps to −128
System.out.println(b);   // prints -128
Overflow/Underflow: Exceeding the max (or min) value rolls the value around within the fixed bit width.

6) Real-World Division Example

Integer division discards the remainder. Cast to get a precise decimal result.

int totalSeconds = 10000;

// Wrong: int / int → int (2), then widened to 2.0
double hoursWrong = totalSeconds / 3600;

// Right: promote to double before dividing
double hoursRight = (double) totalSeconds / 3600;
// 2.777... 

Key Takeaways