exceptions

java.lang.ClassCastException – How to solve ClassCastException

In this tutorial, we will the classcastexception.

This exception is used to indicate that the application’s code has attempted to cast a specific object to a class of which it is not an instance. For example, an Integer object cannot be cast to a String object.

classcastexception

This exception extends the RuntimeException class and thus belongs to those exceptions that can be thrown during the operation of the Java Virtual Machine (JVM). It is an unchecked exception and thus, it does not need to be declared in a method’s or a constructor’s throws clause.

Finally, the ClassCastException exists since the first version of Java.

1. The Structure of ClassCastException

Constructors

  • ClassCastException()

Creates an instance of the ClassCastException class.

  • ClassCastException(String s)

Creates an instance of the ClassCastException class, using the specified string as a message.

2. The ClassCastException in Java

The ClassCastException is related to the type conversion feature offered by modern object-oriented programming languages, where the data type of an entity is changed to another. However, the conversion is valid only in cases where a class extends a parent class and the child class is cast to its parent class.

For example, the following snippet throws a ClassCastException:

ClassCastExceptionExample.java

public class ClassCastExceptionExample {
	public static void main(String[] args) {
		Object obj = new Integer(100);
		System.out.println((String) obj);
	}
}

A sample execution is shown below:

Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
	at main.java.ClassCastExceptionExample.main(ClassCastExceptionExample.java:6)

The next example is more complex and aims to show that an instance of the parent class cannot be casted to an instance of the child class:

ClassCastExceptionExample_v2.java

class Parent {
	public Parent() {
		System.out.println("An instance of the Parent class was created!");
	}
}

final class Child extends Parent {
	public Child() {
		super();
		System.out.println("An instance of the Child class was created!");
	}
}

public class ClassCastExceptionExample_v2 {
	public static void main(String[] args) {
		Parent p = new Parent();
		Child ch = new Child();
		ch = p; //This statement is not allowed.
	}
}

In this example we defined two sample classes, we created one instance of each class and then, tried to cast the instance of the parent class to the instance of its child class. The final statement is not correct and results to a compilation error.

On the other hand, an instance of the parent class can be initialized by an instance of the child class. The following code is correct and does not throw a ClassCastException:

public static void main(String[] args) {
	Parent p = new Parent();
	Child ch = new Child();
	p = ch;
}

3. How to deal with the ClassCastException

  • Be careful when trying to cast an object of a class into another class. Ensure 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.

This was a tutorial about the ClassCastException in Java. Find more about exceptions here.

Last updated on Jan. 10th, 2022

Sotirios-Efstathios Maneas

Sotirios-Efstathios (Stathis) Maneas is a PhD student at the Department of Computer Science at the University of Toronto. His main interests include distributed systems, storage systems, file systems, and operating systems.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
asdfqwerty
asdfqwerty
4 years ago

Hi .I have a class say Deductions(Parent) and tax(Child).I am trying to fetch response which is of type Deductions.And ,then I am trying to set the response in child class object
Deductions response = x;(I am fetching some value related to Deductions through JSON which also have attributes related to Tax also )
Tax tax =(Tax)response.get(0);//I am facing a class cast exception here .Moreover my child class attributes are not fetched when passing through JSON
tax.get(0);

Back to top button