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.
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.
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
java.io.*;
import
java.lang.*;
import
java.util.*;
class
geeks {
public
static
void
main(String[] args)
{
try
{
Object o =
new
Object();
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
java.io.*;
import
java.lang.*;
import
java.util.*;
class
geeks {
public
static
void
main(String[] args)
{
try
{
String s =
"GFG"
;
Object o = (Object)s;
System.out.println(o);
}
catch
(Exception e) {
System.out.println(e);
}
}
}
Introduction to Runtime Exceptions
Runtime exceptions are exceptions which can not be checked at compile time. In Java, there are a myriad of classes derived from the RuntimeException
class [1], all of which represent unchecked exceptions that need to be carefully considered and managed. Despite being less serious and critical than the unchecked runtime errors [2], these exceptions can still be very problematic and cause unexpected issues at runtime, especially if necessary precautions aren’t taken and relevant exception handling mechanisms aren’t put in place.
What is ClassCastException and When does it Happen?
As its name implies, ClassCastException
is an exception that happens when the JVM tries to cast an object to a class (or in some instances, an interface) and fails. This relates to explicit type casting [3] and the reason the cast fails can be traced to an attempt at downcasting an object to a class of which it is not an instance, or to an interface which it does not implement.
ClassCastException
is a subclass of the RuntimeException
class which means it is an unchecked, runtime exception [4]. This exception can not be checked at compile-time because the compiler has no way of knowing whether the object is actually an instance of the target subclass, or if it is an instance of a subclass that implements the target interface. Consequently, if either of these scenarios is encountered at runtime, Java will throw the ClassCastException
exception.
Parent parent = new Child();
/*...*/
Child c = (Child) parent; // is parent actually an instance of Child?
IFace i = (IFace) parent; // Is parent an instance of a subclass that implements IFace?
The only scenario where the compiler is able to detect invalid type casts of this kind is when the source type is a final
class and it neither extends nor implements the target type, because it is known in advance that the final
class does not have any subtypes, i.e., it cannot be subclassed [5].
String s = "s";
IFace i = (IFace) s; // compilation error (the String class is final)
How to handle ClassCastException
To prevent the ClassCastException
exception, one should be careful when casting objects to a specific class or interface and ensure that the target type is a child of the source type, and that the actual object is an instance of that type. To help achieve type safety and catch these issues at compile time, two builtin Java mechanisms are available:
- the
instanceof
operator, and - Generics.
ClassCastException Examples
To better understand ClassCastException
, consider the following Java class hierarchy:
class X {/*...*/}
class Y extends X {/*...*/}
class Z extends X {/*...*/}
Object o = new Z(); // OK
X x = new Y(); // OK
Y y = (Y) x; // OK
y = (Y) o; // Will throw ClassCastException
y = (Y) new X(); // Will throw ClassCastException
Z z = (Z) x; // Will throw ClassCastException
The resulting scenarios can be summarized as follows:
- It is possible to cast an instance of
X
,Y
, orZ
, toObject
, since all Java classes implicitly inherit thejava.lang.Object
class [6]. - It is possible to cast an instance of
Y
orZ
toX
, because they are both subtypes ofX
. - It is possible to cast an instance of type
X
to typeY
(orZ
) ONLY if the original object is of typeY
(orZ
), due to polymorphism [7]. - It is impossible to cast an instance of
Y
toZ
despite the fact that they are both derived fromX
, becauseY
andZ
are unique types with distinct states and behaviors.
Complete examples and ways to deal with ClassCastException
are presented below.
Using the instanceof operator
Java’s instanceof
operator is a binary operator used to test whether the object is an instance of a specific class, or a class that implements a specific interface [8]. When used in the appropriate context, this operator can prevent the ClassCastException
exception from occurring. The code example below shows how trying to cast an instance of Phone
to a subclass of Phone
(Smartphone
) throws the ClassCastException
exception.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package rollbar;
class Phone {}
interface Wireless {
default void charge() {
System.out.println("Phone is charging");
}
}
class Smartphone extends Phone implements Wireless {}
public class ClassCastExceptionExample {
private static final Phone myPhone = new Phone();
public static void main(String... args) {
Smartphone wirelessPhone = (Smartphone) myPhone;
wirelessPhone.charge();
}
}
Exception in thread "main" java.lang.ClassCastException: class rollbar.Phone cannot be cast to class rollbar.Smartphone
at rollbar.ClassCastExceptionExample.main(ClassCastExceptionExample.java:19)
Casting an object to an interface is also a valid polymorphic operation, so one might try to cast the myPhone
variable to a Wireless
instance instead. However, since myPhone
is not an instance of any class that implements Wireless
, the ClassCastException
is thrown again.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package rollbar;
class Phone {}
interface Wireless {
default void charge() {
System.out.println("Phone is charging");
}
}
class Smartphone extends Phone implements Wireless {}
public class ClassCastExceptionExample {
private static final Phone myPhone = new Phone();
public static void main(String... args) {
Wireless wirelessPhone = (Wireless) myPhone;
wirelessPhone.charge();
}
}
Exception in thread "main" java.lang.ClassCastException: class rollbar.Phone cannot be cast to class rollbar.Wireless
at rollbar.ClassCastExceptionExample.main(ClassCastExceptionExample.java:19)
The solution here is to use the instanceOf
operator which will enforce a safe type cast, as shown below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package rollbar;
class Phone {}
interface Wireless {
default void charge() {
System.out.println("Phone is charging");
}
}
class Smartphone extends Phone implements Wireless {}
public class ClassCastExceptionExample {
private static final Phone myPhone = new Phone();
public static void main(String... args) {
if (myPhone instanceof Smartphone smartphone) {
smartphone.charge();
} else {
System.out.println("Phone cannot be charged.");
}
}
}
Phone cannot be charged.
The same concept applies to interfaces:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package rollbar;
class Phone {}
interface Wireless {
default void charge() {
System.out.println("Phone is charging");
}
}
class Smartphone extends Phone implements Wireless {}
public class ClassCastExceptionExample {
private static final Phone myPhone = new Phone();
public static void main(String... args) {
if (myPhone instanceof Wireless wirelessPhone) {
wirelessPhone.charge();
} else {
System.out.println("Phone cannot be charged.");
}
}
}
Phone cannot be charged.
Since myPhone
is neither an instance of Smartphone
nor an instance of a class that implements Wireless
, the instanceOf
operator inside the if
statement evaluates to false, and the corresponding else
clause is executed.
On the other hand, if an object passes the instanceOf
check, then it can be safely cast to the specified type. This can be observed in the example below where the myPhone
variable is an actual instance of the Smartphone
class (as initialized on line 16).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package rollbar;
class Phone {}
interface Wireless {
default void charge() {
System.out.println("Phone is charging");
}
}
class Smartphone extends Phone implements Wireless {}
public class ClassCastExceptionExample {
private static final Phone myPhone = new Smartphone();
public static void main(String... args) {
if (myPhone instanceof Wireless wirelessPhone) {
wirelessPhone.charge();
} else {
System.out.println("Phone cannot be charged.");
}
}
}
Phone is charging.
As a side note, older versions of Java which don’t support pattern matching for the instanceOf
operator [9] will require an extra step to cast the object manually, as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package rollbar;
class Phone {}
interface Wireless {
default void charge() {
System.out.println("Phone is charging");
}
}
class Smartphone extends Phone implements Wireless {}
public class ClassCastExceptionExample {
private static final Phone myPhone = new Smartphone();
public static void main(String... args) {
if (myPhone instanceof Wireless) {
((Wireless) myPhone).charge();
} else {
System.out.println("Phone cannot be charged.");
}
}
}
Phone is charging.
Using Generics & Parameterized Types
Introduced in Java 5, Generics are a very important addition to Java’s type system which brought compile-time type safety and eliminated the need for the tedious type casting when working with the Collections Framework [10]. This mechanism allows programmers to implement generic data structures and algorithms that are type-safe, and it allows Java compilers to perform strong type checking and detect related issues at compile-time.
A parameterized type is an instantiation of a generic type with an actual type argument. The code below shows how the use of raw, unparameterized collections such as List
s can easily lead to the ClassCastException
being triggered. This is because unparameterized collections default to the Object
type, so nothing prevents a program or an API from inserting an instance of an unexpected type into a collection. The example below shows how inserting and later trying to cast the string “200” into a List
instance throws the ClassCastException
exception.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package rollbar;
import java.util.ArrayList;
import java.util.List;
public class ClassCastExceptionGenerics {
private static final List integerList = new ArrayList<>();
public static void main(String... args) {
integerList.add(100);
integerList.add(150);
integerList.add("200");
integerList.forEach(o -> printRoot((Integer) o));
}
public static void printRoot(Integer number) {
if (number != null) {
System.out.println(Math.sqrt(number));
}
}
}
Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer
at rollbar.ClassCastExceptionGenerics.lambda$main$0(ClassCastExceptionGenerics.java:15)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at rollbar.ClassCastExceptionGenerics.main(ClassCastExceptionGenerics.java:15)
Using Generics to make the List
parameterized restricts the types of objects the list can hold to valid instances of Integer
, which in turn makes any attempt to insert any other, incompatible type in the list detectable at compile-time, as shown in the revised example below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package rollbar;
import java.util.ArrayList;
import java.util.List;
public class ClassCastExceptionGenericsFixed {
private static final List<Integer> integerList = new ArrayList<>();
public static void main(String... args) {
integerList.add(100);
integerList.add(150);
integerList.add("200");
integerList.forEach(o -> printRoot((Integer) o));
}
public static void printRoot(Integer number) {
if (number != null) {
System.out.println(Math.sqrt(number));
}
}
}
ClassCastExceptionGenerics.java:13: error: incompatible types: String cannot be converted to Integer
integerList.add("200");
^
1 error
Furthermore, using parameterized types to instantiate Generics eliminates the need to cast collection objects manually, so a working version of the example above could look something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package rollbar;
import java.util.ArrayList;
import java.util.List;
public class ClassCastExceptionGenerics {
private static final List<Integer> integerList = new ArrayList<>();
public static void main(String... args) {
integerList.add(100);
integerList.add(150);
integerList.add(200);
integerList.forEach(o -> printRoot(o));
}
public static void printRoot(Integer number) {
if (number != null) {
System.out.println(Math.sqrt(number));
}
}
}
10.0
12.24744871391589
14.142135623730951
Conclusion
Runtime exceptions are an inevitable evil that all Java programmers have to face at some point. One of these exceptions is the ClassCastException
which is thrown whenever there is an attempt to cast an object to a class or an interface the object is incompatible with. As with other runtime exceptions, being prudent is important and pays off in the long run. This article explains what causes the ClassCastException
by diving into Java’s type casting rules, and it shows how to prevent and effectively deal with this exception by relying on the instanceof
operator and using generic, parameterized types when the situation calls for it.
Track, Analyze and Manage Errors With Rollbar
Managing Java errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!
References
[1] Oracle, 2021. RuntimeException (Java SE 17 & JDK 17). Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/RuntimeException.html. [Accessed Jan. 21, 2022]
[2] Oracle, 2021. Error (Java SE 17 & JDK 17). Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Error.html. [Accessed Jan. 21, 2022]
[3] Rollbar, 2022. How to Handle the Incompatible Types Error in Java. Rollbar Editorial Team. [Online]. Available: https://rollbar.com/blog/how-to-handle-the-incompatible-types-error-in-java/. [Accessed Jan. 21, 2022]
[4] Oracle, 2021. Unchecked Exceptions — The Controversy (The Java™ Tutorials > Essential Java Classes > Exceptions). Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html. [Accessed Jan. 21, 2022]
[5] Oracle, 2021. Writing Final Classes and Methods (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance). Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/javase/tutorial/java/IandI/final.html. [Accessed Jan. 21, 2022]
[6] Oracle, 2021. Inheritance (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance). Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html. [Accessed Jan. 21, 2022]
[7] Oracle, 2021. Polymorphism (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance). Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html. [Accessed Jan. 21, 2022]
[8] Oracle, 2021. Equality, Relational, and Conditional Operators (The Java™ Tutorials > Learning the Java Language > Language Basics). Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html. [Accessed Jan. 21, 2022]
[9] G. Bierman, 2021. JEP 394: Pattern Matching for instanceof. Oracle and/or its affiliates. [Online]. Available: https://openjdk.java.net/jeps/394. [Accessed Jan. 21, 2022]
[10] Oracle, 2021. Why Use Generics? (The Java™ Tutorials > Learning the Java Language > Generics (Updated)). Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/javase/tutorial/java/generics/why.html. [Accessed Jan. 21, 2022]
A quick guide and fix to java lang ClassCastException in java with examples.
1. Overview
In this article, we will learn what is java.lang.ClassCastException in java and how to fix it.
We will look at the meaning of ClassCastException and a few examples of it.
2. What is the meaning of ClassCastException
From API, ClassCastException is thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.
If you are not clear what is ClassCastException then look at the below example.
For example, the following code generates a ClassCastException:
Object x = new Integer(0); System.out.println((String)x);
In this example, we are trying to cast an Integer object into a String. That means converting the Integer object into a String. This operation produced the class cast exception.
The reason behind this error is there is no direct relation between the Integer and String classes.
If there is a Has-a or Is-a relationship between the two classes then the casting is possible, if there is no relation between the classes and if we try to cast it to another class or interface then we get the ClassCastException.
3. Java ClassCastException Examples
A few examples to see in which scenarios we get the class cast exception at runtime.
Example 1
package com.javaprogramto.exception; public class ClassCastExceptionExample { public static void main(String[] args) { Object s = "hello"; Integer i = (Integer) s; } }
Output
Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap') at com.javaprogramto.exception.ClassCastExceptionExample.main(ClassCastExceptionExample.java:8)
Example 2
In this example, class B extends class B that means B is a child of A. Child class object can be assinged to the parent class object but the parenet class object can not be assinged to the child class.
So here we have casted class A instance to class B. This code is resulted in classcastexception.
package com.javaprogramto.exception.classcaseexception; public class ClassCastExceptionExample { public static void main(String[] args) { A a = new A(); B b = (B) a; } } class A { } class B extends A { }
Output
Exception in thread "main" java.lang.ClassCastException: class com.javaprogramto.exception.classcaseexception.A cannot be cast to class com.javaprogramto.exception.classcaseexception.B (com.javaprogramto.exception.classcaseexception.A and com.javaprogramto.exception.classcaseexception.B are in unnamed module of loader 'app') at com.javaprogramto.exception.classcaseexception.ClassCastExceptionExample.main(ClassCastExceptionExample.java:7)
Example 3
package com.javaprogramto.exception.classcaseexception; import java.util.ArrayList; import java.util.List; public class ClassCastExceptionExample2 { public static void main(String[] args) { List list = new ArrayList<>(); list.add(10); list.add(20); list.add("String"); list.add(30); for (int i = 0; i < list.size(); i++) { Integer value = (Integer) list.get(i); System.out.println(value); } } }
Ouptut
10 20 Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap') at com.javaprogramto.exception.classcaseexception.ClassCastExceptionExample2.main(ClassCastExceptionExample2.java:18)
This example is resulted in error becaues of list has string in it and we casted each value of list into Integer. Once it found the string then it is not able to cast into the integer. So, ended up in exception.
4. How to fix ClassCastException
ClassCastException is a unchecked exception that is thrown by the JVM at runtime when you do the invalid or illegal casting is done.
Finding the ClassCastException at the compile time can not be done as similar to the checked exceptions.
So, we must be careful when we do the explicit casting to the different types.
To fix ClassCastException, we need to follow the strict generics when working with the collections API.
In the above section example 3, a list is created without generic type which did not show any error at the compile time but it produces the casting exception at the runtime.
Look at the below code how ClassCastException is eliminated at the compile time.
Example 4
package com.javaprogramto.exception.classcaseexception; import java.util.ArrayList; import java.util.List; public class ClassCastExceptionExample2 { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(10); list.add(20); list.add("String"); list.add(30); for (int i = 0; i < list.size(); i++) { Integer value = (Integer) list.get(i); System.out.println(value); } } }
Output
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method add(Integer) in the type List<Integer> is not applicable for the arguments (String) at com.javaprogramto.exception.classcaseexception.ClassCastExceptionExample2.main(ClassCastExceptionExample2.java:14)
In the above example, the class cast exception is suppressed and caught at the compile time. So we can take out the string from the list.
Another way is to fix class cast exception is with instanceof oeprator.
Example 5
package com.javaprogramto.exception.classcaseexception; public class ClassCastExceptionExample3 { public static void main(String[] args) { C c = new C(); if (c instanceof D) { D d = (D) c; } else { System.out.println("c is not instance of d. skipping.."); } } } class C { } class D extends C { }
Output
c is not instance of d. skipping..
If you know any other ways, please post in the comments we will update the post.
5. Conclusion
In this tutorial, We’ve seen understood the meaning of Java ClassCastException which is present in the java.lang package.
how to fix java.lang.classcaseexception in java.
What We Are Learn On This Post
ClassCastException In Java: In this post, we are going to discuss ClassCastException. 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.
ClassCastException In Java
As you can see in the above pic ClassCast-Exception exception extends the class RuntimeException 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.
java.lang.classcastexception In Java:
An object can be automatically upcasted to its superclass type. You need not mention class type explicitly. But, when an object is supposed to be downcasted to its subclass type, then you have to mention class type explicitly. In such a case, there is a possibility of occurring class cast exception. Most of the time, it occurs when you are trying to downcast an object explicitly to its subclass type.
package co.java.exception; public class ClassCast_Exception { public static void main(String[] args) { Object obj=new Object(); int i=(int) obj; System.out.println(i); } }
Lets Run The Above Program:
When we run the above program we got the below error:
Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.Integer at co.java.exception.ClassCastException.main(ClassCast-Exception.java:8)
Let’s take another example:
package co.java.exception; 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 ClassCast-ExceptionExample { public static void main(String[] args) { Parent p = new Parent(); Child ch = new Child(); ch = (Child) p; //This statement is not allowed. } }
If we run the program then we will get
An instance of the Parent class was created! An instance of the Parent class was created! An instance of the Child class was created! Exception in thread "main" java.lang.ClassCastException: co.java.exception.Parent cannot be cast to co.java.exception.Child at co.java.exception.ClassCastExceptionExample.main(ClassCastExceptionExample.java:20)
Explanation:
In The Above Program, we are creating an instance of both the parent and child class. but when we are trying to assign the parent class instance to child class instance that will generate an exception.
Ref: Article
Reader Interactions
Normally whats the reason to get java.lang.ClassCastException ..? I get the following error in my application
java.lang.ClassCastException: [Lcom.rsa.authagent.authapi.realmstat.AUTHw
krock
28.6k13 gold badges78 silver badges85 bronze badges
asked Aug 18, 2010 at 10:39
1
According to the documentation:
Thrown to indicate that the code has attempted to cast an Object
to a subclass
of which it is not an instance. For example, the following code generates a ClassCastException
:
Object x = new Integer(0);
System.out.println((String)x);
answered Aug 18, 2010 at 10:41
3
A ClassCastException
ocurrs when you try to cast an instance of an Object to a type that it is not. Casting only works when the casted object follows an «is a» relationship to the type you are trying to cast to. For Example
Apple myApple = new Apple();
Fruit myFruit = (Fruit)myApple;
This works because an apple ‘is a’ fruit. However if we reverse this.
Fruit myFruit = new Fruit();
Apple myApple = (Apple)myFruit;
This will throw a ClasCastException because a Fruit is not (always) an Apple.
It is good practice to guard any explicit casts with an instanceof
check first:
if (myApple instanceof Fruit) {
Fruit myFruit = (Fruit)myApple;
}
NoseKnowsAll
4,5332 gold badges23 silver badges44 bronze badges
answered Aug 18, 2010 at 11:19
mR_fr0gmR_fr0g
8,3426 gold badges37 silver badges54 bronze badges
1
@Laurențiu Dascălu’s answer explains how / why you get a ClassCastException.
Your exception message looks rather suspicious to me, but it might help you to know that «[Lcom.rsa.authagent.authapi.realmstat.AUTHw» means that the actual type of the object that you were trying to cast was com.rsa.authagent.authapi.realmstat.AUTHw[]
; i.e. it was an array object.
Normally, the next steps to solving a problem like this are:
- examining the stacktrace to figure out which line of which class threw the exception,
- examining the corresponding source code, to see what the expected type, and
- tracing back to see where the object with the «wrong» type came from.
answered Aug 18, 2010 at 11:08
Stephen CStephen C
688k94 gold badges790 silver badges1200 bronze badges
It’s because you’re casting to the wrong thing — you’re trying to convert to a particular type, and the object that your express refers to is incompatible with that type. For example:
Object x = "this is a string";
InputStream y = (InputStream) x; // This will throw ClassCastException
If you could provide a code sample, that would really help…
answered Aug 18, 2010 at 10:41
Jon SkeetJon Skeet
1.4m851 gold badges9045 silver badges9133 bronze badges
To avoid x !instance of Long
prob
Add
<property name="openjpa.Compatibility" value="StrictIdentityValues=false"/>
in your persistence.xml
oers
18.2k13 gold badges65 silver badges75 bronze badges
answered Feb 2, 2012 at 8:09
ClassA a = <something>;
ClassB b = (ClassB) a;
The 2nd line will fail if ClassA is not a subclass of ClassB, and will throw a ClassCastException.
answered Aug 18, 2010 at 10:42
PaulJWilliamsPaulJWilliams
18.9k3 gold badges50 silver badges79 bronze badges
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.
In this article we’ll see what is java.lang.ClassCastException
and how to resolve ClassCastException in Java.
ClassCastException in Java
ClassCastException is thrown in a Java application when you try to cast an object to a class of which the original object is not an instance i.e. if the class
of which you have an object and the class you are trying to cast that object to are not having a parent-child relationship then casting to that class will result
in ClassCastException.
Exception hierarchy for the ClassCastException in Java is as follows-
Since ClassCastException derives from RuntimeException that means it is an unchecked exception and there is no need to explicitly handle it using try-catch block.
ClassCastException is closely associated to how type casting is done. You can refer this post Type Casting in Java to get better understanding of type casting in Java.
ClassCastException was quite frequently seen before Java generics came into the picture. When collections were not type safe and you needed to explicit cast the elements when retrieving them from the
collection was the fertile ground for the ClassCastException.
ClassCastException Java example
This example shows a scenario where ClassCastException is thrown. Here I have a class hierarchy where Payment is an interface and there are two classes CashPayment
and CardPayment implementing the Payment interface.
Payment interface
public interface Payment { public boolean proceessPayment(double amount); }
CashPayment class
import org.netjs.examples.interfaces.Payment; public class CashPayment implements Payment { @Override public boolean proceessPayment(double amount) { System.out.println("Cash payment done for Rs. " + amount); return true; } }
CardPayment class
import org.netjs.examples.interfaces.Payment; public class CardPayment implements Payment { @Override public boolean proceessPayment(double amount) { System.out.println("Card Payment done for Rs. " + amount); return true; } public void printSlip(){ System.out.println("Printing slip for payment" ); } }
Note that in CardPayment class there is an extra method printSlip().
You do want to follow proper object oriented programming so you refer the instances of child classes CardPayment and CashPayment through the super type instance
Payment. Only to call printSlip() method you will need downcasting to the child class.
import org.netjs.examples.interfaces.Payment; public class PaymentDemo { public static void main(String[] args) { PaymentDemo pd = new PaymentDemo(); Payment payment = new CashPayment(); pd.doPayment(payment, 100); payment = new CardPayment(); pd.doPayment(payment, 300); } public void doPayment(Payment pd, int amt){ pd.proceessPayment(amt); //downcasting CardPayment cardPay = (CardPayment)pd; cardPay.printSlip(); } }
Running this will throw ClassCastException at run time-
Cash payment done for Rs. 100.0 Exception in thread "main" java.lang.ClassCastException: org.netjs.examples.impl.CashPayment cannot be cast to org.netjs.examples.impl.CardPayment at org.netjs.examples.impl.PaymentDemo.doPayment(PaymentDemo.java:17) at org.netjs.examples.impl.PaymentDemo.main(PaymentDemo.java:10)
When instance of CardPayment is passed to Payment reference there is no problem in downcasting it. There is a problem when instance of CashPayment is passed,
widening the reference to Payment is ok but attempting to cast it to CardPayment is not possible as there is no parent-child relationship between these two classes.
Both of them are child classes of Payment and instances of both of these classes are of type Payment but not interchangeable with each other.
Resolving ClassCastException in Java
To ensure that ClassCastException is not thrown you should check for the type of instance using instanceof operator in Java.
public class PaymentDemo { public static void main(String[] args) { PaymentDemo pd = new PaymentDemo(); Payment payment = new CashPayment(); pd.doPayment(payment, 100); payment = new CardPayment(); pd.doPayment(payment, 300); } public void doPayment(Payment pd, int amt){ pd.proceessPayment(amt); if (pd instanceof CardPayment){ CardPayment cardPay = (CardPayment)pd; cardPay.printSlip(); } } }
Output
Cash payment done for Rs. 100.0 Card Payment done for Rs. 300.0 Printing slip for payment
Here note how instanceof operator is used to check the type and casting is done only if correct instance type is found thus avoiding ClassCastException.
That’s all for this topic java.lang.ClassCastException — Resolving ClassCastException in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
- java.lang.ClassNotFoundException — Resolving ClassNotFoundException in Java
- Exception Propagation in Java Exception Handling
- finally Block in Java Exception Handling
- final Vs finally Vs finalize in Java
- Java Exception Handling Interview Questions And Answers
You may also like-
- matches() method in Java String
- Inheritance in Java
- AutoBoxing And UnBoxing in Java
- Reflection in Java — Getting Constructor Information
- Enum Type in Java
- Matrix Addition Java Program
- Spring NamedParameterJdbcTemplate Select Query Example
- Magic Methods in Python With Examples