Java Type Casting
Type casting is how you convert a value from one data type into another in Java. Because Java is strongly typed, the compiler cares a great deal about the type of every value, so knowing when a conversion happens for free and when you must ask for it explicitly is a core skill for any beginner.
What is type casting?
Every value in Java has a type, such as int, double, or char. Sometimes you have a value of one type but need it as another, for example turning a whole number into a decimal so you can divide it accurately. Converting between the primitive numeric types is called type casting, and Java gives you two flavours of it: one that happens automatically and one you have to spell out.
- Widening casting: converting a smaller type into a larger type. Java does this for you automatically because no information can be lost.
- Narrowing casting: converting a larger type into a smaller type. You must write the cast yourself because data can be lost.
- The size order from smallest to largest is: byte, short, char, int, long, float, double.
Widening casting (automatic)
Widening happens when you assign a smaller type to a larger one. The value fits comfortably in the bigger container, so the compiler performs the conversion silently and safely. Notice how the int below becomes a double without any special syntax.
Widening from int to double
public class Main {
public static void main(String[] args) {
int score = 87; // int value
double average = score; // automatically widened to double
System.out.println(score); // 87
System.out.println(average); // 87.0
}
}Narrowing casting (manual)
Narrowing goes the other way, from a larger type down to a smaller one. Because the larger value might not fit, Java refuses to do it automatically and asks you to confirm your intention by writing the target type in parentheses before the value. Any fractional part is simply dropped, not rounded.
Narrowing from double to int
public class Main {
public static void main(String[] args) {
double price = 9.99;
int rounded = (int) price; // manual cast, decimals are cut off
System.out.println(price); // 9.99
System.out.println(rounded); // 9 (not 10 - it truncates)
}
}Casting summary
One more everyday use of casting is fixing integer division. When both operands are int, Java performs integer division and throws away the remainder. Casting one operand to double forces the calculation to keep the decimal part.
Casting to avoid integer division
public class Main {
public static void main(String[] args) {
int total = 7;
int count = 2;
double wrong = total / count; // 3.0 (division done as int first)
double right = (double) total / count; // 3.5 (cast forces decimal math)
System.out.println(wrong);
System.out.println(right);
}
}Exercise: Java Type Casting
What is required to store a double value in an int variable?