I read some articles written on "ClassCastException", but I couldn't get a good idea on what it means. What is a ClassCastException?
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.
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.
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.
// 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With