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
- A primitive cast converts the value.
produces a new number, 9. Information can be lost, and the cast is how you tell the compiler that you accept that.(int) 9.99 - A reference cast converts nothing.
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(Dog) animal if it is wrong.ClassCastException
| Kind | Example | Needs a cast? | Can fail? |
|---|---|---|---|
| Widening primitive | long l = intValue; | No | No, but longdouble |
| Narrowing primitive | (byte) 300 | Yes | Never throws; silently changes the value |
| Upcast | Animal a = dog; | No | No |
| Downcast | (Dog) animal | Yes | ClassCastException |
| Unboxing cast | (int) object | Yes | ClassCastExceptionNullPointerException |
| Unchecked generic | (List<String>) object | Yes, with a warning | Later, at another line |
Primitive casts
The program converts between numeric types in both directions, with values chosen to show each kind of loss: a longdoublebyteshortint
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:
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
and back only approximately, ending in 680: adouble has 53 bits of precision, about 16 digits.double - Integer narrowing keeps the low bits: 300 is 256 + 44, so
is 44, and 70,000 is 65,536 + 4,464.(byte) 300 - Casting a
todouble drops the fraction toward zero (-9.99 becomes -9) and clamps values that do not fit;int becomes 0.NaN rounds instead, with halves going up, so -9.5 becomes -9.Math.round - A cast binds tighter than arithmetic:
converts(double) total / count first and divides as doubles (3.5), whiletotal divides integers first and converts the truncated 3.(double) (total / count) narrowsMath.toIntExact tolong but throws instead of wrapping around.int
The full conversion rules, including promotion in expressions, are on the
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 DogDogAnimal
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:
same object: true
animal.sound(): Woof
animal.name: animal field
((Dog) animal).name: dog field
animal.getClass(): Dog
again.fetch(): fetching the ball
isanimal == dog : the upcast created nothing new.true printed "Woof": overridden methods are chosen by the runtime type. This is polymorphism, covered inanimal.sound()inheritance and polymorphism . printed "animal field" butanimal.name printed "dog field". Fields are not polymorphic:((Dog) animal).name hidesDog.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.name does not compile, because the compiler only knows the variable is ananimal.fetch() . After the downcastAnimal , the same object's(Dog) animal method is reachable.fetch
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.
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:
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
might be aObject , and aString might be anNumber . The JVM checks them when they run.Integer - Cast 3 (line 8) was rejected:
is not a subclass ofString and no class can be both, because a class has only one superclass chain.Number - Casts 4 and 5 show the rule for interfaces. A
could beNumber , since a subclass ofRunnable could implement it, so cast 4 compiled.Number isString and does not implementfinal , so noRunnable can ever beString , and cast 5 (line 10) was rejected.Runnable - Cast 6 (line 11) was rejected because
andArrayList<String> have different type arguments. Cast 7, to the wildcardList<Integer> , is checkable at run time and compiles without warnings.List<?> - Cast 8,
, compiled: since Java 7 an(int) o can be cast to a primitive, meaning "cast toObject , then unbox". Cast 9 (line 14) was rejected: Java has no conversion between numbers andInteger .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 instanceofswitch
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:
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
threw(Square) shape because the object is aClassCastException . The message names both classes, which usually points straight at the wrong assumption.Circle tests the type and, only if it matches, declareso instanceof Circle 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:c .o instanceof String s && !s.isEmpty()- The
over the sealedswitch needs noShape : the compiler knowsdefault andCircle are the only possibilities and checks that both are handled. SeeSquarepattern matching for switch . isnull instanceof Circle , sofalse also acts as a null check. A plain cast ofinstanceof , in contrast, succeeds and givesnull .null
Casts with generics and boxing
Generic types are erased at run time, so the JVM cannot check a cast to List<String>ListClass.cast
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:
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
- The unchecked cast to
succeeded even though the list contained 42. The failure came later, inside the loop, where the compiler had inserted a hidden cast toList<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. SeeStringtype erasure . andClass.isInstance do the same asClass.cast and a cast, for a type held in a variable. Generic code that receives ainstanceof uses them to cast safely.Class<T> worked because the object is an(int) boxed .Integer compiled too, but it means "cast to(long) boxed , then unbox", and anLong is not aInteger :Long . To widen a boxed number, unbox it first:ClassCastException , or((Integer) boxed).longValue() for any numeric type.((Number) boxed).longValue() is an intersection cast: the lambda implements both interfaces, so it can be serialized. Without the cast, a lambda implements only its target interface.(Runnable & Serializable)
Avoiding casts
| Instead of | Prefer |
|---|---|
if (o instanceof Dog) { Dog d = (Dog) o; ... } | if (o instanceof Dog d) { ... } |
A chain of instanceof | A switch |
Raw types and casts to List<String> | Generic types from the start |
(long) objectHoldingAnInteger | ((Number) o).longValue() |
(int) someDouble | Math.roundMath.floorMath.ceil |
(int) someLong | Math.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