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
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.
LinkedInRelated Article - Java Error
- How to Fix the Error: Failed to Create the Java Virtual Machine
- How to Fix the Missing Server JVM Error in Java
- How to Fix the 'No Java Virtual Machine Was Found' Error in Eclipse
- How to Fix Javax.Net.SSL.SSLHandShakeException: Remote Host Closed Connection During Handshake
- How to Fix the Error: Failed to Create the Java Virtual Machine
- How to Fix Java.Lang.VerifyError: Bad Type on Operand Stack