2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

Class Cast Exception ,illustrate and to fix it?

code as follows :

class ClassCastExceptionDemo
{
    public static void main(String args[])
    {
   
    Object ob=new Integer(10);

    // ClassCastException occurs
    System.out.println("The value is "+(String)ob);

           
    }
}

output:

Exception in thread "main" java.lang.ClassCastException: java.lang.Integer canno
t be cast to java.lang.String
        at ClassCastExceptionDemo.main(ClassCastExceptionDemo.java:9)
userimage

The ClassCastException is related to the type conversion feature offered by modern object-oriented programming languages, where the data type of an entity is changed to another. However, the conversion is valid only in cases where a class extends a parent class and the child class is casted to its parent class.

In your case you are trying to cast an Integer type to String type which is quite impossible because of there is no hierarchical relationship in between those two classes.

You can come out from this kind of situation by following below steps :

  • Be careful when trying to cast an object of a class into another class. Ensure that the new type belongs to one of its parent classes.
  • You can prevent the ClassCastException by using Generics, because Generics provide compile time checks and can be used to develop type-safe applications.


Answer is