Two types of casting
Widening (implicit casting)
int → double (32-bit → 64-bit: always safe)
java
int x = 5;
double y = x; // y = 5.0 (automatic — Java converts int to double)
System.out.println(y); // Output: 5.0
Narrowing (explicit casting)
java
double price = 9.99;
int rounded = (int) price; // rounded = 9 (decimal is TRUNCATED, not rounded)
System.out.println(rounded); // Output: 9
java
(int) 3.1 // → 3
(int) 3.9 // → 3 (NOT 4!)
(int) -2.7 // → -2 (truncates toward zero)
(int) 99.999 // → 99
java
double x = 9.99;
int y = x; // ERROR: incompatible types — possible lossy conversion
int z = (int) x; // OK: you're telling Java "I know I might lose data"
Casting in expressions
The integer division problem
java
int a = 7;
int b = 2;
double result1 = a / b; // result1 = 3.0 (int division first → 3 → stored as 3.0)
double result2 = (double) a / b; // result2 = 3.5 (cast a to double → double division)
double result3 = a / (double) b; // result3 = 3.5 (cast b to double → double division)
double result4 = (double) (a / b); // result4 = 3.0 (int division first → 3 → cast to 3.0)
Rounding with casting
java
double price = 3.7;
int rounded = (int) (price + 0.5); // (int) 4.2 = 4 ✓
double price2 = 3.2;
int rounded2 = (int) (price2 + 0.5); // (int) 3.7 = 3 ✓
Automatic type promotion in mixed expressions
java
int x = 5;
double y = 2.5;
double result = x + y; // 5 is promoted to 5.0, result = 7.5
Casting with characters (bonus)
java
char letter = 'A';
int ascii = (int) letter; // ascii = 65
char next = (char) (letter + 1); // next = 'B' (66)
Complete example
java
int total = 97;
int count = 10;
// WRONG way to get average
double avg1 = total / count; // avg1 = 9.0 (NOT 9.7)
// RIGHT way to get average
double avg2 = (double) total / count; // avg2 = 9.7
// Also RIGHT
double avg3 = total * 1.0 / count; // avg3 = 9.7 (multiplying by 1.0 makes it a double)
System.out.println(avg1); // 9.0
System.out.println(avg2); // 9.7
System.out.println(avg3); // 9.7
AP Exam Tips
- •
- •
- •
- •
Common Mistakes
- •
- •
- •
- •