What is ClassCastException in Java: Explanation and Example
ClassCastException in Java happens when you try to convert an object to a class it does not belong to. It is a runtime error that signals an invalid type cast between incompatible classes.How It Works
Imagine you have a box labeled "Fruits" but inside it, there is a toy car. If you try to treat the toy car as an apple just because the box says "Fruits," you will get confused. In Java, objects have specific types, and when you try to treat an object as a different type that it does not actually belong to, Java throws a ClassCastException.
This exception happens at runtime, meaning the program compiles fine but fails when running if the cast is wrong. It is Java's way of protecting you from mixing incompatible types, like trying to use a cat as if it were a dog.
Example
This example shows a ClassCastException when trying to cast a String object to an Integer type, which is not allowed.
public class Main { public static void main(String[] args) { Object obj = "Hello"; // obj holds a String try { Integer num = (Integer) obj; // Wrong cast } catch (ClassCastException e) { System.out.println("Caught exception: " + e); } } }
When to Use
You don't "use" ClassCastException intentionally; instead, you avoid it by ensuring your casts are safe. It often appears when working with collections or APIs that return generic Object types. To prevent it, check the object's type with instanceof before casting.
In real-world programs, this helps avoid crashes when handling data from different sources or when downcasting from a general type to a specific one.
Key Points
- ClassCastException occurs when casting incompatible types.
- It is a runtime exception, not a compile-time error.
- Use
instanceofto check type before casting. - Common in collections or APIs returning generic objects.
- Helps maintain type safety during program execution.