Chathuranga Chandrasekara Chathuranga Chandrasekara - 1 year ago 82
Java Question

Can someone explain "ClassCastException" in Java?

I read some articles written on "ClassCastException" but I couldn't get a good idea on that. Can someone direct me to a good article or explain it briefly.

Answer Source

Straight from the API Specifications for the ClassCastException:

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.

So, for example, when one tries to cast an Integer to a String, String is not an subclass of Integer, so a ClassCastException will be thrown.

Object i = Integer.valueOf(42);
String s = (String)i;            // ClassCastException thrown here.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download