Example: ClassCastException

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.

How to handle the ClassCastException:
– Be careful when trying to transfer an object of one class to another class. Make sure that the new type belongs to one of its parent classes.
– You can prevent the ClassCastException by using generics, because generics provide compile-time checks and can be used to develop type-safe applications.

public class codevisionz {

  public static void main(String[] args) {
    Object obj = new String("Hello");

    try {
      System.out.println((Double)obj);
    } catch (ClassCastException e) {
      System.out.println("This is your problem:");
      System.out.println("Error: " + e);
    }
  }
}
Output
This is your problem:
Error: java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Double (java.lang.String and java.lang.Double are in module java.base of loader 'bootstrap')