CKTIS / Java
lang.ClassCastException: practical reference
lang.ClassCastException: practical reference: ClassCastException signals a run-time cast whose object is incompatible with the requested reference type.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
java.lang.ClassCastExceptionClassCastException signals a run-time cast whose object is incompatible with the requested reference type.
Treat ClassCastException as evidence that the actual object does not satisfy a requested cast; prefer polymorphism or pattern instanceof.
A cast does not convert an object. Raw types and heap pollution can move the failure far from the code that inserted the bad value.
Casting null to a reference type returns null. Casting toward a primitive can first trigger unboxing and its own null failure.
The example exercises the documented element in a small deterministic program and compares exact standard output.
Examples
public class Main {
public static void main(String[] args) throws Exception {
try { String text = (String) (Object) 7; } catch (ClassCastException error) { System.out.println("bad cast"); }
}
}
Result
bad cast
The example exercises the documented element in a small deterministic program and compares exact standard output.