TExcelTAD
Home › Java › Java Type Casting

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)

java · try it yourself
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."

java · try it yourself
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 returns 24.

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:

java · try it yourself
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:

java · try it yourself
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?

  1. 10
  2. 9
  3. 9.99
  4. Compile error

Which conversion happens automatically, without a cast?

  1. double to int
  2. long to int
  3. int to double
  4. int to byte

How do you turn the String "123" into an int?

  1. (int) "123"
  2. Integer.parseInt("123")
  3. "123".toInt()
  4. int("123")