I read some articles written on «ClassCastException», but I couldn’t get a good idea on what it means. What is a ClassCastException?
asked May 25, 2009 at 16:45
0
Straight from the API Specifications for the ClassCastException
:
Thrown to indicate that the code has
attempted to cast an object to a
subclass of which it is not an
instance.
So, for example, when one tries to cast an Integer
to a String
, String
is not an subclass of Integer
, so a ClassCastException
will be thrown.
Object i = Integer.valueOf(42);
String s = (String)i; // ClassCastException thrown here.
answered May 25, 2009 at 16:46
1
It’s really pretty simple: if you are trying to typecast an object of class A into an object of class B, and they aren’t compatible, you get a class cast exception.
Let’s think of a collection of classes.
class A {...}
class B extends A {...}
class C extends A {...}
- You can cast any of these things to Object, because all Java classes inherit from Object.
- You can cast either B or C to A, because they’re both «kinds of» A
- You can cast a reference to an A object to B only if the real object is a B.
- You can’t cast a B to a C even though they’re both A’s.
answered May 25, 2009 at 16:47
Charlie MartinCharlie Martin
109k24 gold badges194 silver badges260 bronze badges
0
It is an Exception which occurs if you attempt to downcast a class, but in fact the class is not of that type.
Consider this heirarchy:
Object -> Animal -> Dog
You might have a method called:
public void manipulate(Object o) {
Dog d = (Dog) o;
}
If called with this code:
Animal a = new Animal();
manipulate(a);
It will compile just fine, but at runtime you will get a ClassCastException
because o was in fact an Animal, not a Dog.
In later versions of Java you do get a compiler warning unless you do:
Dog d;
if(o instanceof Dog) {
d = (Dog) o;
} else {
//what you need to do if not
}
answered May 25, 2009 at 16:49
YishaiYishai
89.5k31 gold badges186 silver badges260 bronze badges
1
Consider an example,
class Animal {
public void eat(String str) {
System.out.println("Eating for grass");
}
}
class Goat extends Animal {
public void eat(String str) {
System.out.println("blank");
}
}
class Another extends Goat{
public void eat(String str) {
System.out.println("another");
}
}
public class InheritanceSample {
public static void main(String[] args) {
Animal a = new Animal();
Another t5 = (Another) new Goat();
}
}
At Another t5 = (Another) new Goat()
: you will get a ClassCastException
because you cannot create an instance of the Another
class using Goat
.
Note: The conversion is valid only in cases where a class extends a parent class and the child class is casted to its parent class.
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.
Source of the Note and the Rest
answered Apr 5, 2013 at 18:58
Do you understand the concept of casting? Casting is the process of type conversion, which is in Java very common because its a statically typed language. Some examples:
Cast the String "1"
to an int
, via Integer.parseInt("1")
-> no problem
Cast the String "abc"
to an int
-> raises a ClassCastException
Or think of a class diagram with Animal.class
, Dog.class
and Cat.class
Animal a = new Dog();
Dog d = (Dog) a; // No problem, the type animal can be casted to a dog, because it's a dog.
Cat c = (Dog) a; // Will cause a compiler error for type mismatch; you can't cast a dog to a cat.
Neuron
4,8435 gold badges36 silver badges54 bronze badges
answered May 25, 2009 at 16:47
Mork0075Mork0075
5,8854 gold badges23 silver badges24 bronze badges
3
A class cast exception is thrown by Java when you try to cast an Object of one data type to another.
Java allows us to cast variables of one type to another as long as the casting happens between compatible data types.
For example you can cast a String as an Object and similarly an Object that contains String values can be cast to a String.
Example
Let us assume we have an HashMap that holds a number of ArrayList objects.
If we write code like this:
String obj = (String) hmp.get(key);
it would throw a class cast exception, because the value returned by the get method of the hash map would be an Array list, but we are trying to cast it to a String. This would cause the exception.
answered Oct 5, 2012 at 11:03
You are trying to treat an object as an instance of a class that it is not. It’s roughly analogous to trying to press the damper pedal on a guitar (pianos have damper pedals, guitars don’t).
answered May 25, 2009 at 16:48
Jeremy HuiskampJeremy Huiskamp
5,1265 gold badges25 silver badges17 bronze badges
A very good example that I can give you for classcastException in Java is while using «Collection»
List list = new ArrayList();
list.add("Java");
list.add(new Integer(5));
for(Object obj:list) {
String str = (String)obj;
}
This above code will give you ClassCastException on runtime. Because you are trying to cast Integer to String, that will throw the exception.
answered Nov 16, 2013 at 17:09
You can better understand ClassCastException and casting once you realize that the JVM cannot guess the unknown. If B is an instance of A it has more class members and methods on the heap than A. The JVM cannot guess how to cast A to B since the mapping target is larger, and the JVM will not know how to fill the additional members.
But if A was an instance of B, it would be possible, because A is a reference to a complete instance of B, so the mapping will be one-to-one.
answered Apr 2, 2013 at 10:05
MistrielMistriel
4494 silver badges9 bronze badges
Exception is not a subclass of RuntimeException -> ClassCastException
final Object exception = new Exception();
final Exception data = (RuntimeException)exception ;
System.out.println(data);
answered Jul 5, 2020 at 8:50
LalikLalik
1111 silver badge6 bronze badges
A Java ClassCastException is an Exception that can occur when you try to improperly convert a class from one type to another.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ClassCastExceptionExample {
public ClassCastExceptionExample() {
List list = new ArrayList();
list.add("one");
list.add("two");
Iterator it = list.iterator();
while (it.hasNext()) {
// intentionally throw a ClassCastException by trying to cast a String to an
// Integer (technically this is casting an Object to an Integer, where the Object
// is really a reference to a String:
Integer i = (Integer)it.next();
}
}
public static void main(String[] args) {
new ClassCastExceptionExample();
}
}
If you try to run this Java program you’ll see that it will throw the following ClassCastException:
Exception in thread "main" java.lang.ClassCastException: java.lang.String
at ClassCastExceptionExample (ClassCastExceptionExample.java:15)
at ClassCastExceptionExample.main (ClassCastExceptionExample.java:19)
The reason an exception is thrown here is that when I’m creating my list object, the object I store in the list is the String “one,” but then later when I try to get this object out I intentionally make a mistake by trying to cast it to an Integer. Because a String cannot be directly cast to an Integer — an Integer is not a type of String — a ClassCastException is thrown.
answered Dec 17, 2017 at 18:13
If you want to sort objects but if class didn’t implement Comparable or Comparator, then you will get ClassCastException
For example
class Animal{
int age;
String type;
public Animal(int age, String type){
this.age = age;
this.type = type;
}
}
public class MainCls{
public static void main(String[] args){
Animal[] arr = {new Animal(2, "Her"), new Animal(3,"Car")};
Arrays.sort(arr);
}
}
Above main method will throw below runtime class cast exception
Exception in thread «main» java.lang.ClassCastException: com.default.Animal cannot be cast to java.lang.Comparable
Sociopath
12.9k18 gold badges45 silver badges73 bronze badges
answered Sep 18, 2018 at 5:28
karepukarepu
1861 silver badge6 bronze badges
ClassCastException in Java occurs when we try to convert the data type of entry into another. This is related to the type conversion feature and data type conversion is successful only where a class extends a parent class and the child class is cast to its parent class.
Here we can consider parent class as vehicle and child class may be car, bike, cycle etc., Parent class as shape and child class may be 2d shapes or 3d shapes, etc.
Two different kinds of constructors available for ClassCastException.
- ClassCastException(): It is used to create an instance of the ClassCastException class.
- ClassCastException(String s): It is used to create an instance of the ClassCastException class, by accepting the specified string as a message.
Let us see in details
Java
import
java.math.BigDecimal;
public
class
ClassCastExceptionExample {
public
static
void
main(String[] args)
{
Object sampleObject =
new
BigDecimal(
10000000.45
);
System.out.println(sampleObject);
}
}
Output
10000000.4499999992549419403076171875
If we try to print this value by casting to different data type like String or Integer etc., we will be getting ClassCastException.
Java
import
java.math.BigDecimal;
public
class
Main {
public
static
void
main(String[] args)
{
Object sampleObject =
new
BigDecimal(
10000000.45
);
System.out.println((String)sampleObject);
}
}
Output :
Exception in thread “main” java.lang.ClassCastException: class java.math.BigDecimal cannot be cast to class java.lang.String (java.math.BigDecimal and java.lang.String are in module java.base of loader ‘bootstrap’)
at Main.main(Main.java:11)
We can fix the exception printing by means of converting the code in the below format:
Java
import
java.math.BigDecimal;
public
class
ClassCastExceptionExample {
public
static
void
main(String[] args)
{
Object sampleObject =
new
BigDecimal(
10000000.45
);
System.out.println(String.valueOf(sampleObject));
}
}
Output
10000000.4499999992549419403076171875
So, in any instances when we try to convert data type of object, we cannot directly downcast or upcast to a specified data type. Direct casting will not work and it throws ClassCastException. Instead, we can use
String.valueOf() method. It converts different types of values like int, long, boolean, character, float etc., into the string.
- public static String valueOf(boolean boolValue)
- public static String valueOf(char charValue)
- public static String valueOf(char[] charArrayValue)
- public static String valueOf(int intValue)
- public static String valueOf(long longValue)
- public static String valueOf(float floatValue)
- public static String valueOf(double doubleValue)
- public static String valueOf(Object objectValue)
are the different methods available and in our above example, the last method is used.
Between Parent and Child class. Example shows that the instance of the parent class cannot be cast to an instance of the child class.
Java
class
Vehicle {
public
Vehicle()
{
System.out.println(
"An example instance of the Vehicle class to proceed for showing ClassCastException"
);
}
}
final
class
Bike
extends
Vehicle {
public
Bike()
{
super
();
System.out.println(
"An example instance of the Bike class that extends Vehicle as parent class to proceed for showing ClassCastException"
);
}
}
public
class
ClassCastExceptionExample {
public
static
void
main(String[] args)
{
Vehicle vehicle =
new
Vehicle();
Bike bike =
new
Bike();
Bike bike1 =
new
Vehicle();
bike = vehicle;
}
}
Compiler error :
In order to overcome Compile-time errors, we need to downcast explicitly. i.e. downcasting means the typecasting of a parent object to a child object. That means features of parent object lost and hence there is no implicit downcasting possible and hence we need to do explicitly as below way
Giving the snippet where the change requires. In the downcasting Explicit way
Java
class
Vehicle {
String vehicleName;
void
displayData()
{
System.out.println(
"From Vehicle class"
);
}
}
class
Bike
extends
Vehicle {
double
cost;
@Override
void
displayData()
{
System.out.println(
"From bike class"
+ cost);
}
}
public
class
ClassCastExceptionExample {
public
static
void
main(String[] args)
{
Vehicle vehicle =
new
Bike();
vehicle.vehicleName =
"BMW"
;
Bike bike = (Bike)vehicle;
bike.cost =
1000000
;
System.out.println(bike.vehicleName);
System.out.println(bike.cost);
bike.displayData();
}
}
Output
BMW 1000000.0 From bike class1000000.0
Upcasting implicit way
An example for upcasting of the child object to the parent object. It can be done implicitly. This facility gives us the flexibility to access the parent class members.
Java
class
Vehicle {
String vehicleName;
void
displayData()
{
System.out.println(
"From Vehicle class"
);
}
}
class
Bike
extends
Vehicle {
double
cost;
@Override
void
displayData()
{
System.out.println(
"From bike class..."
+ cost);
}
}
public
class
ClassCastExceptionExample {
public
static
void
main(String[] args)
{
Vehicle vehicle =
new
Bike();
vehicle.vehicleName =
"Harley-Davidson"
;
System.out.println(vehicle.vehicleName);
vehicle.displayData();
}
}
Output
Harley-Davidson From bike class...0.0
Fixing ClassCastException in an upcasting way and at the same time, loss of data also occurs
Java
class
Vehicle {
public
Vehicle()
{
System.out.println(
"An example instance of the Vehicle class to proceed for showing ClassCast Exception"
);
}
public
String display()
{
return
"Vehicle class display method"
;
}
}
class
Bike
extends
Vehicle {
public
Bike()
{
super
();
System.out.println(
"An example instance of the Bike class that extends nVehicle as parent class to proceed for showing ClassCast Exception"
);
}
public
String display()
{
return
"Bike class display method"
;
}
}
public
class
ClassCastExceptionExample {
public
static
void
main(String[] args)
{
Vehicle vehicle =
new
Vehicle();
Bike bike =
new
Bike();
vehicle = bike;
System.out.println(
"After upcasting bike(child) to vehicle(parent).."
+ vehicle.display());
}
}
Output
An example instance of the Vehicle class to proceed for showing ClassCast Exception An example instance of the Vehicle class to proceed for showing ClassCast Exception An example instance of the Bike class that extends Vehicle as parent class to proceed for showing ClassCast Exception After upcasting bike(child) to vehicle(parent)..Bike class display method
Conclusion: By means of either upcasting or downcasting, we can overcome ClassCastException if we are following Parent-child relationships. String.valueOf() methods help to convert the different data type to String and in that way also we can overcome.
1. Overview
In this short tutorial, we’ll focus on ClassCastException, a common Java exception.
ClassCastException is an unchecked exception that signals the code has attempted to cast a reference to a type of which it’s not a subtype.
Let’s look at some scenarios that lead to this exception being thrown and how we can avoid them.
2. Explicit Casting
For our next experiments, let’s consider the following classes:
public interface Animal {
String getName();
}
public class Mammal implements Animal {
@Override
public String getName() {
return "Mammal";
}
}
public class Amphibian implements Animal {
@Override
public String getName() {
return "Amphibian";
}
}
public class Frog extends Amphibian {
@Override
public String getName() {
return super.getName() + ": Frog";
}
}
2.1. Casting Classes
By far, the most common scenario for encountering a ClassCastException is explicitly casting to an incompatible type.
For example, let’s try to cast a Frog to a Mammal:
Frog frog = new Frog();
Mammal mammal = (Mammal) frog;
We might expect a ClassCastException here, but in fact, we get a compilation error: “incompatible types: Frog cannot be converted to Mammal”. However, the situation changes when we use the common super-type:
Animal animal = new Frog();
Mammal mammal = (Mammal) animal;
Now, we get a ClassCastException from the second line:
Exception in thread "main" java.lang.ClassCastException: class Frog cannot be cast to class Mammal (Frog and Mammal are in unnamed module of loader 'app')
at Main.main(Main.java:9)
A checked downcast to Mammal is incompatible from a Frog reference because Frog is not a subtype of Mammal. In this case, the compiler cannot help us, as the Animal variable may hold a reference of a compatible type.
It’s interesting to note that the compilation error only occurs when we attempt to cast to an unequivocally incompatible class. The same is not true for interfaces because Java supports multiple interface inheritance, but only single inheritance for classes. Thus, the compiler can’t determine if the reference type implements a specific interface or not. Let’s exemplify:
Animal animal = new Frog();
Serializable serial = (Serializable) animal;
We get a ClassCastException on the second line instead of a compilation error:
Exception in thread "main" java.lang.ClassCastException: class Frog cannot be cast to class java.io.Serializable (Frog is in unnamed module of loader 'app'; java.io.Serializable is in module java.base of loader 'bootstrap')
at Main.main(Main.java:11)
2.2. Casting Arrays
We’ve seen how classes handle casting, now let’s look at arrays. Array casting works the same as class casting. However, we might get confused by autoboxing and type-promotion, or lack thereof.
Thus, let’s see what happens for primitive arrays when we attempt the following cast:
Object primitives = new int[1];
Integer[] integers = (Integer[]) primitives;
The second line throws a ClassCastException as autoboxing doesn’t work for arrays.
How about type promotion? Let’s try the following:
Object primitives = new int[1];
long[] longs = (long[]) primitives;
We also get a ClassCastException because the type promotion doesn’t work for entire arrays.
2.3. Safe Casting
In the case of explicit casting, it is highly recommended to check the compatibility of the types before attempting to cast using instanceof.
Let’s look at a safe cast example:
Mammal mammal;
if (animal instanceof Mammal) {
mammal = (Mammal) animal;
} else {
// handle exceptional case
}
3. Heap Pollution
As per the Java Specification: “Heap pollution can only occur if the program performed some operation involving a raw type that would give rise to a compile-time unchecked warning”.
For our experiment, let’s consider the following generic class:
public static class Box<T> {
private T content;
public T getContent() {
return content;
}
public void setContent(T content) {
this.content = content;
}
}
We will now attempt to pollute the heap as follows:
Box<Long> originalBox = new Box<>();
Box raw = originalBox;
raw.setContent(2.5);
Box<Long> bound = (Box<Long>) raw;
Long content = bound.getContent();
The last line will throw a ClassCastException as it cannot transform a Double reference to Long.
4. Generic Types
When using generics in Java, we must be wary of type erasure, which can lead to ClassCastException as well in some conditions.
Let’s consider the following generic method:
public static <T> T convertInstanceOfObject(Object o) {
try {
return (T) o;
} catch (ClassCastException e) {
return null;
}
}
And now let’s call it:
String shouldBeNull = convertInstanceOfObject(123);
At first look, we can reasonably expect a null reference returned from the catch block. However, at runtime, due to type erasure, the parameter is cast to Object instead of String. Thus the compiler is faced with the task of assigning an Integer to String, which throws ClassCastException.
5. Conclusion
In this article, we have looked at a series of common scenarios for inappropriate casting.
Whether implicit or explicit, casting Java references to another type can lead to ClassCastException unless the target type is the same or a descendent of the actual type.
The code used in this article can be found over on GitHub.