Open In App

How to Solve Class Cast Exceptions in Java?

Last Updated : 02 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

An unexcepted, unwanted event that disturbed the normal flow of a program is called Exception. Most of the time exceptions are caused by our program and these are recoverable. Example: If our program requirement is to read data from the remote file locating at the U.S.A. At runtime, if the remote file is not available then we will get RuntimeException saying fileNotFoundException. If fileNotFoundException occurs we can provide the local file to the program to read and continue the rest of the program normally.

There are mainly two types of exception in java as follows:

1. Checked Exception: The exception which is checked by the compiler for the smooth execution of the program at runtime is called a checked exception. In our program, if there is a chance of rising checked exceptions then compulsory we should handle that checked exception (either by try-catch or throws keyword) otherwise we will get a compile-time error.

Examples of checked exceptions are classNotFoundException, IOException, SQLException etc.

2. Unchecked Exception: The exceptions which are not checked by the compiler, whether programmer handling or not such type of exception are called an unchecked exception.

Examples of unchecked exceptions are ArithmeticException, ArrayStoreException etc.

Whether the exception is checked or unchecked every exception occurs at run time only if there is no chance of occurring any exception at compile time.

ClassCastException: It is the child class of RuntimeException and hence it is an unchecked exception. This exception is rise automatically by JVM whenever we try to improperly typecast a class from one type to another i.e when we’re trying to typecast parent object to child type or when we try to typecast an object to a subclass of which it is not an instance.

In the below program we create an object o of type Object and typecasting that object o to a String object s. As we know that Object class is the parent class of all classes in java and as we’re trying to typecast a parent object to its child type then ultimately we get java.lang.ClassCastException

Java




// import required packages
import java.io.*;
import java.lang.*;
import java.util.*;
// driver class
class geeks {
   
    // main method
    public static void main(String[] args)
    {
        try {
           
            // creating an object
            Object o = new Object();
           
            // type casting the object o to string which
            // give the classcasted exception because we
            // type cast an parent type to its child type.
            String s = (String)o;
           
            System.out.println(s);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}


 
 

Output

java.lang.ClassCastException: class java.lang.Object cannot be cast to class java.lang.String (java.lang.Object and java.lang.String are in module java.base of loader 'bootstrap')

In order to deal with ClassCastException be careful that when you’re trying to typecast an object of a class into another class ensure that the new type belongs to one of its parent classes or do not try to typecast a parent object to its child type. While using Collections we can prevent ClassCastException by using generics because generics provide the compile-time checking.

Below is the implementation of the problem statement:

Java




// import required packages
import java.io.*;
import java.lang.*;
import java.util.*;
 
// driver class
class geeks {
   
    // main method
    public static void main(String[] args)
    {
        try {
           
            // creating an object
            String s = "GFG";
            Object o = (Object)s;
           
            // Object class is parent class of every class
            // Hence exception doesn't occur.
            System.out.println(o);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}


Output

GFG


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads