java.lang.ClassCastException is a RuntimeException in Java and hence the Java Compiler will not check for it.
ClassCastException occurs when you try to cast an object to a subclass of which it is not an instance, i.e. when the object that you are trying to cast is not compatible with the target type.
Below is an example of code that generate a ClassCastException:
import java.util.ArrayList;
import java.util.List;
public class ClassCastExceptionExample {
public static void main(String[] args) {
List list = new ArrayList();
list.add(10);
list.add("Hello");
String str = (String) list.get(0); //ClassCastException
}
}
Here we have a list as a raw type so we can add Objects of any types without any issues, but it becomes really difficult to know what elements will the list return, this if you try to cast the element incorrectly we get a ClassCastExceptionExample at runtime.
Fix or ClassCastExceptionExample
It is always recommended to make use of Java Generics that were introduced with Java 1.5 instead of raw types. By using Generics you add type safety to your code and thus you do not need to do casting.
public static void main(String[] args) {
List<String> list = new ArrayList<>();
//list.add(10); //incompatible types: int cannot be converted to java.lang.String
list.add("Hello");
String str = (String) list.get(0);
}
Instead you will get a Complication Error saying "incompatible types: int cannot be converted to java.lang.String". Thus you can avoid runtime exceptions.
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
Thanks for your feedback! If you have time, please provide details by selecting options below.
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!