Fix - java.lang.ClassCastException

java.lang.ClassCastException is a Runtime Exception 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

java ClassCastException Example

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!