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

    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.

java ClassCastException Example

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap