java.lang.ClassCastException in Java

Shiv Yadav Feb 15, 2024
  1. the java.lang.ClassCastException in Java
  2. Resolve the java.lang.ClassCastException in Java
java.lang.ClassCastException in Java

When we attempt to cast an object from the parent class to the object of the child class, the java.lang.ClassCastException is raised. It may, however, also be thrown if we attempt to convert an object between two entirely unrelated types.

This article will help you handle Java’s java.lang.ClassCastException.

the java.lang.ClassCastException in Java

The program below creates an object obb of type Object and types that object obb to an object shh of type String. As we are trying to typecast an object to its child type, we end up with Java.lang because we know that the Object class is the parent class of all classes in Java.ClassCastException.

Code - classCast.java:

public class classCast {
  public static void main(String[] args) {
    try {
      Object obb = new Object();

      String shh = (String) obb;

      System.out.println(shh);
    } catch (Exception e) {
      System.out.println(e);
    }
  }
}

Output:

java.lang.Object cannot be cast to java.lang.String

Resolve the java.lang.ClassCastException in Java

Make sure the new type belongs to one of the parent classes of the class you’re trying to typecast an object from, or avoid typecasting a parent object to its child type to prevent encountering the ClassCastException. Generics, which offer compile-time validation, can be used to prevent ClassCastException while utilizing Collections.

It is an unchecked exception since it is a RuntimeException child class. When we attempt to inappropriately typecast a course from one type to another, such as when we try to typecast a parent object to a child type or typecast an object to a subclass that isn’t an instance, the JVM raises this exception automatically.

Code - classCast.java:

package classcaste;

public class classCast {
  public static void main(String[] args) {
    try {
      String shh = "shiv";
      Object obb = (Object) shh;

      System.out.println(obb);
    } catch (Exception e) {
      System.out.println(e);
    }
  }
}

Output:

shiv
Author: Shiv Yadav
Shiv Yadav avatar Shiv Yadav avatar

Shiv is a self-driven and passionate Machine learning Learner who is innovative in application design, development, testing, and deployment and provides program requirements into sustainable advanced technical solutions through JavaScript, Python, and other programs for continuous improvement of AI technologies.

LinkedIn

Related Article - Java Error