Home » Java Basics » exceptions » java.lang.ClassCastException – How to solve Class Cast Exception

About Sotirios-Efstathios Maneas

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.

java.lang.ClassCastException – How to solve Class Cast Exception

In this tutorial we will discuss about 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 casted to a String object.

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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

 

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 message.

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 casted 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;
}

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.

(-6 rating, 8 votes)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of