Monday, December 22, 2014

ClassCastException in Java

ClassCastException exception is thrown when an attempt is made to cast between incompatible types (such as String to Integer type or vice versa).  In this article, we understand this exception in more detail and find out the way to avoid this exception with examples.

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. For example, the following code generates a ClassCastException:
Object x = new Integer(0);

Take a look at the above figure to review the class hierarchy of this exception. Examine the code where the line of code that throws the ClassCastException is shown in bold.

ClassCastException is thrown when an object fails an IS-A test with the class type to which it’s being cast. In the preceding example, class Ink is the base class for classes ColorInk and BlackInk. The JVM throws a ClassCastException in the previous case because the line of code in bold tries to explicitly cast an object of ColorInk to BlackInk.

Why above code avoided the compilation error
Note that above line of code avoided the compilation error because the variable inks defines an ArrayList of type Ink , which is capable of storing objects of type Ink and all its subclasses. The code then correctly adds the allowed objects: one each of BlackInk and ColorInk.

If the code had defined an ArrayList of type BlackInk or ColorInk , the code would have failed the compilation, as follows:
Here’s the compilation error thrown by the previously modified piece of code:

How to avoid ClassCastException
If a ClassCastException is thrown while executing a program, and if there are no exception handlers for that, the program will terminate. So, how about providing an exception handler like this?
Yes, this will work and the program will not crash. But this is a really bad idea! There are two main problems in this code.

  • Providing exception handlers for RuntimeExceptions like this create an illusion that the program is working perfectly fine, when it is not!
  • Runtime exceptions like ClassCastException indicate programming errors and should not be caught using exception handlers.
Okay, so what do you do now? Before downcasting, check for the dynamic type of the object and then downcast. You can use the instanceof operator to verify whether an object can be cast to another class before casting it.

This is an effective and proper way to achieve downcasting. Using the instanceof operator checks the dynamic type of obj, which helps you to decide whether to downcast it to a String object.

Continue with our main example. Assuming that the definition of classes Ink , ColorInk, and BlackInk are the same as defined in the previous example, the following lines of code will avoid the ClassCastException

In the previous example, the condition ( inks.get(0)instanceofBlackInk ) evaluates to false , so the then part of the if statement doesn’t execute.

Try to examine and share the output of the following program in comment section

If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

1 comment:

  1. I am technology Enthusiast. Your blog is really awesome, attractive and impressive. I like the way you think. it is very useful for Java SE & Java EE Learners. Your article adds best knowledge to our Java Online Training in India. or learn thru Java Online Training in India Students. or learn thru JavaScript Online Training in India. Appreciating the persistence you put into your blog and detailed information you provide. Kindly keep blogging.