HOWTO · Java
java.lang.ClassCastException in Java
Learn why Java throws java.lang.ClassCastException, how to identify an incompatible runtime type, and how to prevent or handle an unsafe cast.
On this page
A java.lang.ClassCastException means an object’s runtime type is not compatible with the type requested by a cast. To fix it, compare the actual object type with the cast target, then use instanceof, typed generics, or a different design so the cast is valid. Catch the exception only when the program has a useful recovery action.
What Is a ClassCastException?
Java allows a cast when the types are related in a way that could be valid at runtime. The cast does not change the object. At runtime, Java checks whether that object is an instance of the target class or implements the target interface. If it is not, Java throws java.lang.ClassCastException.
For example, if Dog and Cat both extend Animal, an Animal reference can refer to either object. Casting an Animal reference to Dog is valid only when the referenced object is actually a Dog. A Cat object cannot be cast to its sibling type Dog. By contrast, assigning a Dog to an Animal reference is an upcast and is safe because every Dog is an Animal.
Why Does Java Throw a ClassCastException?
The usual cause is an assumption that a broadly typed reference contains a particular subclass. The compiler can check that a downcast is structurally possible, but it cannot always know which object will be stored there at runtime. The runtime check catches the mismatch.
This often appears when code receives values as Object, uses a legacy collection without generics, or makes assumptions about the concrete class returned by an API. Polymorphism itself is not the problem: calling an overridden method through a parent-class reference is safe. The failure occurs when code tries to narrow that reference to a subtype the object does not have.
Raw collections and unchecked conversions can also bypass generic type checks. A later retrieval may insert an implicit cast and fail when the value is used. Find where the value entered the collection and where its type was assumed; changing only the line that throws may hide the source of the mismatch.
How to Prevent a ClassCastException
Prefer declaring references and collections with the most specific useful type. Generics let the compiler check collection insertions and retrievals, reducing the need for casts. They do not make an explicit cast of an arbitrary object safe, and raw types or unchecked operations can still undermine their protection.
A downcast can compile when the source and target classes are related, then fail if the object is actually a sibling subtype. This example catches the failure so the program can finish normally:
public class FailingCastExample {
static class Animal {}
static class Dog extends Animal {}
static class Cat extends Animal {}
public static void main(String[] args) {
Animal animal = new Cat();
try {
Dog dog = (Dog) animal;
System.out.println(dog);
} catch (ClassCastException exception) {
System.out.println(exception.getClass().getName());
}
}
}
java.lang.ClassCastException
The catch receives java.lang.ClassCastException: the object is a Cat, not a Dog. The JVM-generated message and stack trace can vary by runtime, so use the exception type and the cast line to diagnose the mismatch. Keep the value typed as Animal when subtype-specific behavior is unnecessary.
When a value is intentionally broad, check its runtime type before narrowing it. This self-contained example shows a safe cast:
public class CastExample {
static class Animal {
String name() { return "Milo"; }
}
static class Dog extends Animal {
String bark() { return "woof"; }
}
public static void main(String[] args) {
Animal animal = new Dog();
if (animal instanceof Dog) {
Dog dog = (Dog) animal;
System.out.println(dog.bark());
}
}
}
The cast is guarded by instanceof, so it runs only when the object is a Dog. If no subtype-specific behavior is needed, keep the value typed as Animal and use its shared API instead. On Java versions that support pattern matching for instanceof, the check and binding can be combined; this example uses the traditional syntax for broad compatibility.
How to Handle and Diagnose a ClassCastException
Read the exception message and stack trace to identify the source type, requested target type, and line where the cast occurs. Then trace the value back to its source: inspect the returned object, collection contents, deserialization mapping, or API contract. Add a type check or correct the declared data model at the point where the assumption is made.
A try-catch block is appropriate when a failed cast is an expected input condition and the program can recover, such as rejecting one malformed record while processing others. Catching ClassCastException around ordinary application logic and continuing without correcting the assumption can leave data incomplete or conceal a bug. Keep the try block narrow and report enough context to diagnose the offending value. No exception message is shown here because its wording can vary by Java implementation and runtime version.
Frequently Asked Questions
What is java.lang.ClassCastException?
For a class target, Java throws it when the object is not an instance of that class; for an interface target, Java throws it when the object does not implement that interface. A cast to the object’s own class or to a compatible superclass or interface succeeds.
How can I avoid ClassCastException in Java?
Use precise declared types and generics, and check with instanceof before a downcast when the runtime type is not already guaranteed. These steps reduce unsafe casts; they cannot make every arbitrary cast valid.
What happens if I do not handle it?
If it is not caught, it propagates up the current thread’s call stack and may terminate that thread’s work. The effect on the whole application depends on the thread and its surrounding error handling.
Can ClassCastException be caught with try-catch?
Yes. Catch it when recovery is meaningful. Otherwise, fix the incompatible cast or the source of the incorrect type assumption.
Is using instanceof a good practice?
Use it when behavior genuinely depends on an object’s runtime subtype. If repeated type checks are spreading through the code, consider moving subtype-specific behavior into polymorphic methods or redesigning the data model.