Java Type Casting
Type casting means converting a value from one type to another. Java does some conversions automatically and requires you to ask explicitly for the risky ones.
Widening casting (automatic)
Converting a smaller type to a larger one can never lose the value's magnitude, so Java does it for you:
byte → short → int → long → float → double (and char → int)
class Main {
public static void main(String[] args) {
int apples = 12;
long bigApples = apples; // int -> long
double precise = apples; // int -> double
char letter = 'A';
int code = letter; // char -> int
System.out.println(bigApples);
System.out.println(precise);
System.out.println(code);
}
}12
12.0
65
Narrowing casting (manual)
Going from a larger type to a smaller one might lose information, so you must write the target type in parentheses. You are telling the compiler: "I know, do it anyway."
class Main {
public static void main(String[] args) {
double temperature = 23.87;
int whole = (int) temperature; // fraction is cut off, not rounded
System.out.println(whole);
double negative = -7.9;
System.out.println((int) negative);
int big = 300;
byte small = (byte) big; // 300 doesn't fit in a byte
System.out.println(small);
int code = 97;
System.out.println((char) code);
}
}23
-7
44
a
| Cast | What happens |
|---|---|
double → int |
Decimal part is truncated toward zero (-7.9 → -7) |
int → byte |
Only the lowest 8 bits are kept, so the value can wrap (300 → 44) |
int → char |
The number is read as a Unicode code (97 → 'a') |
Tip: To round instead of truncating, use
Math.round(23.87)which returns24.
Casting in calculations
Arithmetic on two ints produces an int, even if the result "should" be a fraction. Cast one operand to double before dividing:
class Main {
public static void main(String[] args) {
int correct = 7;
int total = 9;
System.out.println(correct / total); // int division
System.out.println((double) correct / total); // double division
double percent = (double) correct / total * 100;
System.out.printf("Score: %.1f%%%n", percent);
System.out.println((double) (correct / total)); // too late!
}
}0
0.7777777777777778
Score: 77.8%
0.0
The last line shows a common mistake: the division already happened as integers, so casting the result 0 gives 0.0.
Converting between strings and numbers
Casting does not work between String and numbers. Use library methods instead:
class Main {
public static void main(String[] args) {
String text = "42";
int number = Integer.parseInt(text);
double d = Double.parseDouble("3.5");
System.out.println(number + 8);
System.out.println(d * 2);
String back = String.valueOf(number);
String also = "" + d;
System.out.println(back + "!" + also);
try {
Integer.parseInt("forty-two");
} catch (NumberFormatException e) {
System.out.println("Not a number: " + e.getMessage());
}
}
}50
7.0
42!3.5
Not a number: For input string: "forty-two"
Test yourself
What is the value of (int) 9.99?
- 10
- 9
- 9.99
- Compile error
Which conversion happens automatically, without a cast?
- double to int
- long to int
- int to double
- int to byte
How do you turn the String "123" into an int?
- (int) "123"
- Integer.parseInt("123")
- "123".toInt()
- int("123")