How to Fix java.lang.classcastexception in Java?
Last Updated :
12 Dec, 2022
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)
{
// Creating a BigDecimal object
Object sampleObject = new BigDecimal(10000000.45);
System.out.println(sampleObject);
}
}
Output10000000.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)
{
// Creating a BigDecimal object
Object sampleObject = new BigDecimal(10000000.45);
// Trying to display the object by casting to String
// As the object is created as BigDecimal but tried
// to display by casting to String,
// ClassCastException is thrown
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)
{
// Creating a BigDecimal object
Object sampleObject = new BigDecimal(10000000.45);
// We can avoid ClassCastException by this way
System.out.println(String.valueOf(sampleObject));
}
}
Output10000000.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();
// Check out for this statement. Tried to convert
// parent(vehicle) object to child object(bike).
// Here compiler error is thrown
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
// An easier way to understand Downcasting
class Vehicle {
String vehicleName;
// Method in parent class
void displayData()
{
System.out.println("From Vehicle class");
}
}
class Bike extends Vehicle {
double cost;
// Overriding the parent class method and we can
// additionally mention about the child class
@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";
// Downcasting Explicitly
Bike bike = (Bike)vehicle;
bike.cost = 1000000;
// Though vehiclename is not assigned, it takes BMW
// as it is
System.out.println(bike.vehicleName);
System.out.println(bike.cost);
bike.displayData();
}
}
OutputBMW
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
// An easier way to understand Upcasting
class Vehicle {
String vehicleName;
// Method in parent class
void displayData()
{
System.out.println("From Vehicle class");
}
}
class Bike extends Vehicle {
double cost;
// Overriding the parent class method and we can
// additionally mention about the child class
@Override void displayData()
{
System.out.println("From bike class..." + cost);
}
}
public class ClassCastExceptionExample {
public static void main(String[] args)
{
// Upcasting
Vehicle vehicle = new Bike();
vehicle.vehicleName = "Harley-Davidson";
// vehicle.cost //not available as upcasting done
// but originally Vehicle class dont have cost
// attribute
System.out.println(vehicle.vehicleName);
vehicle.displayData(); // Hence here we will get
// output as 0.0
}
}
OutputHarley-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(); // Vehicle class constructor msg display as
// super() is nothing but calling parent
// method
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();
// But we can make bike point to vehicle, i.e.
// pointing child object to parent object This is an
// example for upcasting of child object to parent
// object. It can be done implicitly This facility
// gives us the flexibility to access the parent
// class members
vehicle = bike;
// As upcasted here, vehicle.display() will provide
// "Bike class display method" as output It has lost
// its parent properties as now vehicle is nothing
// but bike only
System.out.println(
"After upcasting bike(child) to vehicle(parent).."
+ vehicle.display());
}
}
OutputAn 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.
Similar Reads
How to Solve java.lang.ClassNotFoundException in Java?
In Java, java.lang.ClassNotFoundException is a checked exception and occurs when the Java Virtual Machine (JVM) tries to load a particular class and the specified class cannot be found in the classpath. ClassNotFoundException should be handled with a try-catch block or using the throw keyword. In ol
4 min read
How to Solve Class Cast Exceptions in Java?
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 fi
3 min read
java.lang.reflect.Constructor Class in Java
java.lang.reflect.Constructor class is used to manage the constructor metadata like the name of the constructors, parameter types of constructors, and access modifiers of the constructors. We can inspect the constructors of classes and instantiate objects at runtime. The Constructor[] array will hav
4 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It
15+ min read
Java.lang.Class class in Java | Set 2
Java.lang.Class class in Java | Set 1 More methods: 1. int getModifiers() : This method returns the Java language modifiers for this class or interface, encoded in an integer. The modifiers consist of the Java Virtual Machine's constants for public, protected, private, final, static, abstract and in
15+ min read
java.lang.reflect.Field Class in Java
The ability of the software to analyze itself is known as Reflection. This is provided by the java.lang.reflect package and elements in Class .Field serves the same purpose as the whole reflection mechanism, analyze a software component and describe its capabilities dynamically, at run time rather t
5 min read
How to Resolve Java.lang.ExceptionInInitializerError In Java?
An unexpected, unwanted event that disturbed the normal flow of a program is called an Exception. There are mainly two types of exception in Java: 1. Checked Exception 2. Unchecked Exception ExceptionInInitializerError is the child class of the Error class and hence it is an unchecked exception. Thi
3 min read
Java.lang.System class in Java
Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array. It extends class
15 min read
java.lang.MethodType Class in Java
MethodType is a Class that belongs to java.lang package. This class consists of various types of methods that help in most of cases to find the method type based on the input object, or parameters of the method. All the instances of methodType are immutable. This means the objects of the methodType
4 min read
java.net.BindException in Java with Examples
The java.net.BindException is an exception that is thrown when there is an error caused in binding when an application tries to bind a socket to a local address and port. Mostly, this may occur due to 2 reasons, either the port is already in use(due to another application) or the address requested j
2 min read