Type Casting
Type casting is converting a value from one data type to another. Java supports two kinds: implicit (widening) casting, which the compiler does for you automatically, and explicit (narrowing) casting, which you must write yourself because it can lose information.
Implicit (Widening) Casting
Widening casting happens automatically when you assign a smaller data type to a larger one — for example, an
int to a double. No data is lost because the bigger type can always represent the
smaller one's range.
public class WideningExample {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // automatic widening, no cast needed
System.out.println(myInt); // 9
System.out.println(myDouble); // 9.0
}
}
The typical widening order is byte → short → char → int → long → float → double. Moving left-to-right along this chain is always safe.
Explicit (Narrowing) Casting
Narrowing casting converts a larger type into a smaller one — for example, a double into an
int. This must be done manually with the (type) syntax, because it can lose data
(the compiler forces you to acknowledge that risk).
public class NarrowingExample {
public static void main(String[] args) {
double myDouble = 9.78;
int myInt = (int) myDouble; // explicit narrowing
System.out.println(myDouble); // 9.78
System.out.println(myInt); // 9 (the .78 is truncated, not rounded)
}
}
9.78 to int gives 9, not 10. Casting very large numbers into a smaller type can also wrap around to unexpected values.Casting Between char and int
Every char in Java is backed by a numeric character code (its Unicode value). Casting a
char to an int gives you that code; casting an int back to
char gives you the character at that code.
public class CharIntExample {
public static void main(String[] args) {
char myChar = 'A';
int code = myChar; // implicit widening, char -> int
System.out.println(code); // 65
int num = 66;
char letter = (char) num; // explicit narrowing, int -> char
System.out.println(letter); // B
}
}
Quick Reference
| Casting type | Direction | Syntax | Risk |
|---|---|---|---|
| Implicit (widening) | Small type → big type | Automatic, no cast written | None — safe |
| Explicit (narrowing) | Big type → small type | (type) value | Possible data loss / truncation |