06
Oct

ClassCastException in java

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

Object i = Integer.valueOf(100);
String s = (String)i;

Solution: 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.