Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation of ClassCastException in Java

I read some articles written on "ClassCastException", but I couldn't get a good idea on what it means. What is a ClassCastException?

like image 384
Chathuranga Chandrasekara Avatar asked May 25 '09 16:05

Chathuranga Chandrasekara


People also ask

How would you explain a ClassCastException in Java?

ClassCast Exception in Java is one of the unchecked exceptions that occur when we try to convert one class type object into another class type. ClassCast Exception is thrown when we try to cast an object of the parent class to the child class object.

Is ClassCastException checked or unchecked?

ClassCastException is one of the unchecked exception in Java. It can occur in our program when we tried to convert an object of one class type into an object of another class type.

What is a ClassCastException and how do we avoid it?

To prevent the ClassCastException exception, one should be careful when casting objects to a specific class or interface and ensure that the target type is a child of the source type, and that the actual object is an instance of that type.

How do you solve ClassCastException in Java?

// type cast an parent type to its child type. In order to deal with ClassCastException be careful that when you're trying to typecast an object of a class into another class ensure that the new type belongs to one of its parent classes or do not try to typecast a parent object to its child type.


1 Answers

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. 
like image 196
coobird Avatar answered Oct 16 '22 20:10

coobird