Casting and type conversion

Core Java · lesson 21 of 42 · 4 min read

Widen for free, narrow on purpose, and tell a primitive cast from a reference cast.

Open this lesson in the learning hub

Key points

  • Widening (int to long to double) is automatic, because nothing can be lost.
  • Narrowing needs an explicit cast and can lose data: (byte) 130 wraps round to -126.
  • A cast on a double truncates toward zero. Use Math.round when you actually want rounding.
  • The division happens before the assignment, so double d = 7 / 2; is 3.0. Cast an operand instead.
  • Casting a reference converts nothing — it re-labels the type and throws ClassCastException if the object is something else.
  • instanceof with a pattern variable tests and casts in one step, so that cast can never fail.

Example

public class Main {

    static String describe(Object o) {
        if (o instanceof Integer i) return "Integer doubled: " + (i * 2);
        if (o instanceof String s) return "String upper: " + s.toUpperCase();
        return "no branch matched: " + o.getClass().getSimpleName();
    }

    public static void main(String[] args) {
        int small = 42;
        long wide = small;
        double d = wide;
        System.out.println("widening int -> long -> double: " + d);

        double price = 9.99;
        System.out.println("(int) 9.99      = " + (int) price + "  (truncates, never rounds)");
        System.out.println("Math.round(9.99) = " + Math.round(price));

        System.out.println("(byte) 130      = " + (byte) 130 + "  (wraps past 127)");
        System.out.println("int / int       = " + (7 / 2) + ", (double) 7 / 2 = " + ((double) 7 / 2));

        System.out.println("text to number: " + (Integer.parseInt("21") * 2));
        System.out.println("number to text: " + String.valueOf(21).repeat(2));

        System.out.println(describe(7));
        System.out.println(describe("java"));
        System.out.println(describe(3.5));

        Object o = "not a number";
        try {
            Integer n = (Integer) o;
            System.out.println(n);
        } catch (ClassCastException e) {
            System.out.println("bad reference cast -> ClassCastException");
        }
    }
}

Widening is safe, narrowing truncates, and a reference cast only re-labels.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.