java.lang.ClassCastException in Java

Shiv Yadav Feb 15, 2024 Java Java Error
  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:

shiv
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
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