Java Type Casting

Java type casting converts a value from one type to another. Some conversions happen automatically because no information can be lost; others you must request explicitly because data might be cut off.

Widening Casting (Automatic)

Converting a smaller type to a larger one is safe, so Java does it for you: byte to short to int to long to float to double.

public class Main {
    public static void main(String[] args) {
        int count = 42;
        long bigCount = count;
        double asDouble = count;
        System.out.println(bigCount);
        System.out.println(asDouble);
    }
}
42
42.0

Narrowing Casting (Manual)

Going from a larger type to a smaller one can lose data, so you must write the target type in parentheses. Casting a double to int drops the decimal part; it does not round.

public class Main {
    public static void main(String[] args) {
        double price = 9.99;
        int whole = (int) price;
        long rounded = Math.round(price);
        System.out.println(whole);
        System.out.println(rounded);
        System.out.println((char) 66);
    }
}
9
10
B

Integer Division Pitfall

When both operands are int, Java does integer division and throws away the remainder. Cast one operand to double to get a decimal result.

public class Main {
    public static void main(String[] args) {
        int correct = 7, total = 9;
        System.out.println(correct / total * 100);
        System.out.println((double) correct / total * 100);
    }
}
0
77.77777777777779

Converting Strings and Numbers

Casting does not work between String and numbers. Use the parse methods to read numbers from text and String.valueOf (or concatenation) to go the other way.

public class Main {
    public static void main(String[] args) {
        int qty = Integer.parseInt("12");
        double rate = Double.parseDouble("2.5");
        String text = String.valueOf(qty * rate);
        System.out.println(text + " (length " + text.length() + ")");
    }
}
30.0 (length 4)

If the text is not a valid number, parseInt throws a NumberFormatException. You will learn to handle that in the Exceptions lesson.

Frequently asked questions

How do I convert a double to an int in Java?

Use (int) value to truncate the decimal part, or Math.round(value) to round to the nearest whole number (it returns a long for a double).

How do I convert a String to an int in Java?

Call Integer.parseInt("123"). It throws NumberFormatException if the string is not a valid integer.

Why does 5 / 2 equal 2 in Java?

Both values are int, so Java performs integer division and discards the remainder. Write 5 / 2.0 or cast one side to double to get 2.5.