Loading lessons...
Type Casting
Type Casting
Type casting is converting one data type into another. Java has two kinds: widening (automatic) and narrowing (manual).
Widening casting (automatic)
Converting a smaller type to a larger type happens automatically:
int myInt = 9;
double myDouble = myInt; // Automatic: int -> double
System.out.println(myDouble); // 9.0
Order of automatic conversion:
byte -> short -> char -> int -> long -> float -> double
Narrowing casting (manual)
Converting a larger type to a smaller type must be done manually by placing the type in parentheses:
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual: double -> int
System.out.println(myInt); // 9
Casting to string and back
String s = Integer.toString(123); // "123"
int n = Integer.parseInt("456"); // 456
Why casting matters
Widening is safe because no data is lost. Narrowing can lose data: converting 9.78 to an int drops the decimal and gives 9.
TL;DR
- Widening (smaller to larger) happens automatically.
- Narrowing (larger to smaller) needs an explicit cast in parentheses.
- Use
Integer.parseInt()andInteger.toString()to convert between String and int.