Casting in Java

A cast tells the compiler to treat a value as a different type. For numbers it really converts the value, sometimes losing information. For objects it changes nothing about the object, only which methods the compiler lets you call, and the JVM checks it when the code runs. This page explains both kinds, shows exactly which casts javac rejects and why, and covers the ClassCastExceptions that come from generics and boxing.

Contents

Two very different operations

The same syntax, (Type) expression, means two different things depending on the type:

  • A primitive cast converts the value. (int) 9.99 produces a new number, 9. Information can be lost, and the cast is how you tell the compiler that you accept that.
  • A reference cast converts nothing. (Dog) animal produces the same object; it only changes the static type, the type the compiler uses to decide which methods and fields you may use. Because the compiler cannot always know what the object really is, the JVM checks every downcast at run time and throws ClassCastException if it is wrong.
Kinds of casts
KindExampleNeeds a cast?Can fail?
Widening primitivelong l = intValue;NoNo, but long to double can lose precision
Narrowing primitive(byte) 300YesNever throws; silently changes the value
UpcastAnimal a = dog;NoNo
Downcast(Dog) animalYesClassCastException at run time
Unboxing cast(int) objectYesClassCastException or NullPointerException
Unchecked generic(List<String>) objectYes, with a warningLater, at another line

Primitive casts

The program converts between numeric types in both directions, with values chosen to show each kind of loss: a long too precise for a double, integers too large for byte and short, fractions, and values far outside the int range.

Java
public class NumericCasts {

    public static void main(String[] args) {
        // Widening: automatic, never loses the magnitude
        int i = 1000;
        long l = i;
        double d = l;
        System.out.println("int -> long -> double: " + d);

        // ... but long and int to float/double can lose precision
        long bigLong = 123456789012345678L;
        double asDouble = bigLong;
        System.out.println("long:                  " + bigLong);
        System.out.println("long -> double -> long " + (long) asDouble);

        // Narrowing: needs an explicit cast, keeps only the low bits
        int big = 300;
        byte b = (byte) big;
        System.out.println("(byte) 300 = " + b + "   (300 - 256)");
        System.out.println("(short) 70000 = " + (short) 70000);
        System.out.println("(char) 65 = " + (char) 65 + ", (int) 'A' = " + (int) 'A');

        // double -> int truncates toward zero and saturates at the int range
        System.out.println("(int) 9.99 = " + (int) 9.99 + ", (int) -9.99 = " + (int) -9.99);
        System.out.println("Math.round(9.5) = " + Math.round(9.5) + ", Math.round(-9.5) = "
                + Math.round(-9.5));
        System.out.println("(int) 1e20 = " + (int) 1e20 + ", (int) NaN = " + (int) Double.NaN);
        System.out.println("(long) 1e20 = " + (long) 1e20);

        // Cast binds tighter than division
        int total = 7;
        int count = 2;
        System.out.println("(double) total / count = " + (double) total / count);
        System.out.println("(double) (total / count) = " + (double) (total / count));

        // Safe narrowing
        try {
            Math.toIntExact(5000000000L);
        } catch (ArithmeticException e) {
            System.out.println("Math.toIntExact: " + e.getMessage());
        }
    }
}

Output:

Output
int -> long -> double: 1000.0
long:                  123456789012345678
long -> double -> long 123456789012345680
(byte) 300 = 44   (300 - 256)
(short) 70000 = 4464
(char) 65 = A, (int) 'A' = 65
(int) 9.99 = 9, (int) -9.99 = -9
Math.round(9.5) = 10, Math.round(-9.5) = -9
(int) 1e20 = 2147483647, (int) NaN = 0
(long) 1e20 = 9223372036854775807
(double) total / count = 3.5
(double) (total / count) = 3.0
Math.toIntExact: integer overflow
  • 123,456,789,012,345,678 survived the trip to double and back only approximately, ending in 680: a double has 53 bits of precision, about 16 digits.
  • Integer narrowing keeps the low bits: 300 is 256 + 44, so (byte) 300 is 44, and 70,000 is 65,536 + 4,464.
  • Casting a double to int drops the fraction toward zero (-9.99 becomes -9) and clamps values that do not fit; NaN becomes 0. Math.round rounds instead, with halves going up, so -9.5 becomes -9.
  • A cast binds tighter than arithmetic: (double) total / count converts total first and divides as doubles (3.5), while (double) (total / count) divides integers first and converts the truncated 3.
  • Math.toIntExact narrows long to int but throws instead of wrapping around.

The full conversion rules, including promotion in expressions, are on the data types page.

Static type and runtime type

Every reference has two types: the static type of the variable, known to the compiler, and the runtime type of the object, known only when the program runs. A cast changes only the static type. The program holds one Dog through a Dog variable and an Animal variable and shows which type decides what.

Java
public class StaticAndRuntimeType {

    static class Animal {
        String name = "animal field";

        String sound() {
            return "...";
        }
    }

    static class Dog extends Animal {
        String name = "dog field";                 // hides Animal.name, does not override it

        @Override
        String sound() {
            return "Woof";
        }

        String fetch() {
            return "fetching the ball";
        }
    }

    public static void main(String[] args) {
        Dog dog = new Dog();
        Animal animal = dog;                       // upcast: automatic, always safe

        System.out.println("same object:           " + (animal == dog));
        System.out.println("animal.sound():        " + animal.sound());   // runtime type
        System.out.println("animal.name:           " + animal.name);      // static type
        System.out.println("((Dog) animal).name:   " + ((Dog) animal).name);
        System.out.println("animal.getClass():     " + animal.getClass().getSimpleName());

        // animal.fetch() does not compile: the static type Animal has no fetch()
        Dog again = (Dog) animal;                  // downcast: checked when it runs
        System.out.println("again.fetch():         " + again.fetch());
    }
}

Output:

Output
same object:           true
animal.sound():        Woof
animal.name:           animal field
((Dog) animal).name:   dog field
animal.getClass():     Dog
again.fetch():         fetching the ball
  • animal == dog is true: the upcast created nothing new.
  • animal.sound() printed "Woof": overridden methods are chosen by the runtime type. This is polymorphism, covered in inheritance and polymorphism.
  • animal.name printed "animal field" but ((Dog) animal).name printed "dog field". Fields are not polymorphic: Dog.name hides Animal.name, and the static type picks which one is read. Static methods behave the same way. Avoid hiding fields; it is legal but confusing.
  • animal.fetch() does not compile, because the compiler only knows the variable is an Animal. After the downcast (Dog) animal, the same object's fetch method is reachable.

Which casts compile

javac rejects a reference cast when it can prove the cast could never succeed. The program compiles nine casts that look similar and prints the ones javac rejects, with its messages. The numbers in the comments match the line order.

Java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

// Compiles casts that look similar and prints the ones javac rejects
public class CastRules {

    static final String SOURCE = """
            import java.util.ArrayList;
            import java.util.List;

            class Casts {
                void test(Object o, Number n, ArrayList<String> list) {
                    String a = (String) o;            // 1 OK: Object might be a String
                    Integer b = (Integer) n;          // 2 OK: Number might be an Integer
                    String c = (String) n;            // 3 error: no Number is a String
                    Runnable d = (Runnable) n;        // 4 OK: a Number subclass could be Runnable
                    Runnable e = (Runnable) "text";   // 5 error: String is final
                    List<Integer> f = (List<Integer>) list;   // 6 error: generics differ
                    List<?> g = (List<?>) o;          // 7 OK: wildcard, no warning
                    int h = (int) o;                  // 8 OK: Object -> Integer -> int
                    boolean i = (boolean) 1;          // 9 error: no numeric/boolean casts
                }
            }
            """;

    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("casts");
        Path file = dir.resolve("Casts.java");
        Files.writeString(file, SOURCE);
        JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
        ByteArrayOutputStream err = new ByteArrayOutputStream();
        javac.run(null, null, new PrintStream(err, true, StandardCharsets.UTF_8),
                "-d", dir.toString(), file.toString());
        err.toString(StandardCharsets.UTF_8).lines()
                .filter(l -> l.startsWith(file.toString()))
                .map(l -> l.substring(dir.toString().length() + 1))
                .forEach(System.out::println);
    }
}

Output:

Output
Casts.java:8: error: incompatible types: Number cannot be converted to String
Casts.java:10: error: incompatible types: String cannot be converted to Runnable
Casts.java:11: error: incompatible types: ArrayList<String> cannot be converted to List<Integer>
Casts.java:14: error: incompatible types: int cannot be converted to boolean
  • Casts 1 and 2 compiled: an Object might be a String, and a Number might be an Integer. The JVM checks them when they run.
  • Cast 3 (line 8) was rejected: String is not a subclass of Number and no class can be both, because a class has only one superclass chain.
  • Casts 4 and 5 show the rule for interfaces. A Number could be Runnable, since a subclass of Number could implement it, so cast 4 compiled. String is final and does not implement Runnable, so no String can ever be Runnable, and cast 5 (line 10) was rejected.
  • Cast 6 (line 11) was rejected because ArrayList<String> and List<Integer> have different type arguments. Cast 7, to the wildcard List<?>, is checkable at run time and compiles without warnings.
  • Cast 8, (int) o, compiled: since Java 7 an Object can be cast to a primitive, meaning "cast to Integer, then unbox". Cast 9 (line 14) was rejected: Java has no conversion between numbers and boolean.

Downcasts that fail, and pattern matching

A downcast that compiles can still be wrong when it runs. The program makes one correct and one wrong downcast, then uses the safer forms that test and cast in one step: pattern matching for instanceof (Java 16) and for switch over a sealed interface (Java 21).

Java
public class ReferenceCasts {

    sealed interface Shape permits Circle, Square {
    }

    record Circle(double r) implements Shape {
    }

    record Square(double side) implements Shape {
    }

    static String describe(Object o) {
        // Pattern matching for instanceof (Java 16): test and cast in one step
        if (o instanceof Circle c) {
            return "circle with radius " + c.r();
        }
        if (o instanceof String s && !s.isEmpty()) {
            return "string of length " + s.length();
        }
        return "something else: " + o;
    }

    static double area(Shape s) {
        // Pattern matching for switch (Java 21): no default needed for a sealed type
        return switch (s) {
            case Circle c -> Math.PI * c.r() * c.r();
            case Square q -> q.side() * q.side();
        };
    }

    public static void main(String[] args) {
        Object shape = new Circle(2);                 // upcast: automatic
        Circle back = (Circle) shape;                 // downcast: explicit, checked at run time
        System.out.println("downcast ok: " + back);

        try {
            Square wrong = (Square) shape;
            System.out.println(wrong);
        } catch (ClassCastException e) {
            String msg = e.getMessage();
            System.out.println("ClassCastException: " + msg.substring(0, msg.indexOf(" (")));
        }

        System.out.println(describe(shape));
        System.out.println(describe("hello"));
        System.out.println(describe(42));
        System.out.printf("areas: %.2f and %.2f%n", area(new Circle(1)), area(new Square(3)));

        // instanceof is false for null, so it doubles as a null check
        Object nothing = null;
        System.out.println("null instanceof Circle: " + (nothing instanceof Circle));
    }
}

Output:

Output
downcast ok: Circle[r=2.0]
ClassCastException: class ReferenceCasts$Circle cannot be cast to class ReferenceCasts$Square
circle with radius 2.0
string of length 5
something else: 42
areas: 3.14 and 9.00
null instanceof Circle: false
  • (Square) shape threw ClassCastException because the object is a Circle. The message names both classes, which usually points straight at the wrong assumption.
  • o instanceof Circle c tests the type and, only if it matches, declares c already cast. The test and the cast cannot get out of step, as they can when the two are written separately. The pattern can be combined with further conditions: o instanceof String s && !s.isEmpty().
  • The switch over the sealed Shape needs no default: the compiler knows Circle and Square are the only possibilities and checks that both are handled. See pattern matching for switch.
  • null instanceof Circle is false, so instanceof also acts as a null check. A plain cast of null, in contrast, succeeds and gives null.

Casts with generics and boxing

Generic types are erased at run time, so the JVM cannot check a cast to List<String>; it only checks that the object is a List. The program shows the delayed failure this causes, the reflective Class.cast, a boxing cast that fails surprisingly, and an intersection cast for a lambda.

Java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class GenericAndBoxingCasts {

    @SuppressWarnings("unchecked")
    static List<String> namesFrom(Object raw) {
        return (List<String>) raw;                 // unchecked: nothing is verified here
    }

    public static void main(String[] args) {
        // 1. An unchecked cast fails later, far from where it was written
        List<Object> mixed = new ArrayList<>(List.of("Ana", 42));
        List<String> names = namesFrom(mixed);     // no exception here
        System.out.println("cast succeeded, size " + names.size());
        try {
            for (String name : names) {            // the hidden cast to String fails here
                System.out.println("name: " + name);
            }
        } catch (ClassCastException e) {
            System.out.println("ClassCastException while looping: Integer is not a String");
        }

        // 2. Class.cast and isInstance: casts with a type known only at run time
        Object value = "hello";
        Class<String> type = String.class;
        if (type.isInstance(value)) {
            System.out.println("Class.cast: " + type.cast(value).toUpperCase());
        }

        // 3. Casting an Object to a primitive unboxes, but only from the matching wrapper
        Object boxed = 42;                         // an Integer
        int asInt = (int) boxed;
        System.out.println("(int) Object holding Integer: " + asInt);
        try {
            long asLong = (long) boxed;            // compiles as a cast to Long
            System.out.println(asLong);
        } catch (ClassCastException e) {
            System.out.println("(long) Object holding Integer: ClassCastException");
        }
        System.out.println("((Integer) boxed).longValue(): " + ((Integer) boxed).longValue());

        // 4. An intersection cast gives a lambda two interfaces at once
        Runnable task = (Runnable & Serializable) () -> System.out.println("task ran");
        task.run();
        System.out.println("lambda is Serializable: " + (task instanceof Serializable));
    }
}

Output:

Output
cast succeeded, size 2
name: Ana
ClassCastException while looping: Integer is not a String
Class.cast: HELLO
(int) Object holding Integer: 42
(long) Object holding Integer: ClassCastException
((Integer) boxed).longValue(): 42
task ran
lambda is Serializable: true
  1. The unchecked cast to List<String> succeeded even though the list contained 42. The failure came later, inside the loop, where the compiler had inserted a hidden cast to String for each element: "Ana" printed, then 42 failed. In a real program that line can be in another class, written by someone else. javac warns about unchecked casts for this reason; suppress the warning only after making sure the cast is safe. See type erasure.
  2. Class.isInstance and Class.cast do the same as instanceof and a cast, for a type held in a variable. Generic code that receives a Class<T> uses them to cast safely.
  3. (int) boxed worked because the object is an Integer. (long) boxed compiled too, but it means "cast to Long, then unbox", and an Integer is not a Long: ClassCastException. To widen a boxed number, unbox it first: ((Integer) boxed).longValue(), or ((Number) boxed).longValue() for any numeric type.
  4. (Runnable & Serializable) is an intersection cast: the lambda implements both interfaces, so it can be serialized. Without the cast, a lambda implements only its target interface.

Avoiding casts

Alternatives to casting
Instead ofPrefer
if (o instanceof Dog) { Dog d = (Dog) o; ... }if (o instanceof Dog d) { ... } (Java 16)
A chain of instanceof checksA switch with type patterns over a sealed type (Java 21), or a polymorphic method
Raw types and casts to List<String>Generic types from the start
(long) objectHoldingAnInteger((Number) o).longValue()
(int) someDouble when rounding was meantMath.round, Math.floor or Math.ceil
(int) someLongMath.toIntExact

A downcast in ordinary business code is often a sign that a method belongs on the class itself: rather than asking "is this a Dog?" and casting, call an overridden method and let each class answer for itself.