Java lang classcastexception как исправить

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.

  1. ClassCastException(): It is used to create an instance of the ClassCastException class.
  2. 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. 

  1. public static String valueOf(boolean boolValue)
  2. public static String valueOf(char charValue)
  3. public static String valueOf(char[] charArrayValue)
  4. public static String valueOf(int intValue)
  5. public static String valueOf(long longValue)
  6. public static String valueOf(float floatValue)
  7. public static String valueOf(double doubleValue)
  8. 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 :

Compile time error occurrence when tried to convert parent object to child object

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.

Last Updated :
12 Dec, 2022

Like Article

Save Article

Disclosure: This article may contain affiliate links. When you purchase, we may earn a small commission.

As name suggests ClassCastException in Java
comes when we try to type cast an object and object is not of the type we are
trying to cast into. In fact
ClassCastException in Java is
one of most common exception in Java along with java.lang.OutOfMemoryError
and ClassNotFoundException
in Java before Generics was introduced in Java 5 to avoid frequent
instances of
java.lang.classcastexception cannot be cast to while
working with Collection classes like ArrayList
and HashMap,
which were not type-safe before Java 5. Though we can minimize and avoid java.lang.ClassCastException
in Java by
using Generics and writing type-safe
parameterized classes and method, its good to know real cause of ClassCastException
and How to
solve it.



In this Java tutorial we will see Why java.lang.ClassCastException
comes and how to resolve ClassCastException in Java. We
will also see how to minimize or avoid ClassCastException
in Java by
using Generics,
as prevention is always better than cure.

Cause of java.lang.ClassCastException in Java

How to fix java.lang.ClassCastException in Java cause and solutionIn order to understand cause of ClassCastException, you need
to be familiar with concept of type
casting in Java. Since Java is an object oriented programming language and
supports features like Inheritance and Polymorphism, a reference variable of
type parent class can represent object of child class. This leads to
ClassCastException
if object is not of type on which you are casting it. It can be best
explained with an example. Let’s see a sample code which will throw ClassCastException
in Java:

Object imObject = new
String();
Integer i = (Integer) imObject;

Above code will throw

Exception in thread “main”
java.lang.ClassCastException: java.lang.String cannot be cast to
java.lang.Integer

at
test.ClassCastExcetpionTest.main(ClassCastExcetpionTest.java:31)

If you see closely we were trying to cast an String object
into an
Integer object which is not correct and
that’s why Java throws java.lang.classcastexception cannot be cast to error
. Problems can become more
difficult if all class are closely related. 



Since due to polymorphism
in Java an Object instance can hold any type of Object but you can only
cast between same type. what makes this problem worse is that it only comes
during runtime,
ClassCastException doesn’t come at compile time
which makes it hard to detect specially in large enterprise Java application or
high frequency electronic trading system where input comes from upstream and in
production various kinds of input are available. 



This was frequent problem with
Java Collection classes like LinkedList
and HashSet
in Java which holds Object type but with introduction of Generics
in Java 5 solved this problem by checking type-safety during compile time. Which
means you can not store Integers on LinkedList of String, from Java 5 it will
result in compile time error.




Common
source of java.lang.ClassCastException

Following are some of the most common source of ClassCastExcepiton in
Java:

1. Java Collection classes like HashMap, ArrayList, Vector
or
Hashtable which is not using Generics.

2. Methods which were written to take advantage of polymorphic behavior
and coded on interfaces prior to Java 5 and doesn’t used parameter to provide
type-safety. 
look for all places where you have used cast operator in Java and verify
that whether that code is type-safe or not.

Here are some of the most frequently occurred ClassCastException in Java:

java.lang.classcastexception java.lang.string cannot be cast to java.lang.integer

This will come when you try to cast String object to Integer i.e.
Integer number = (Integer) stringObject;

java.lang.classcastexception java.lang.string cannot be cast to java.util.date :
This error will come when you cast String to Date in Java, since both are not related to each other, it will not possible to typecast them.

java.lang.classcastexception java.util.arraylist cannot be cast to java.lang.string
I have seen this happening a lot in beginners code based on Java Collection framework, Since ArrayList and String are not related to each other, following casting will throw this error :

String str = (String) arrayListObject;

But if you definitely wants to convert ArrayList to String, than check this post about converting collection to String in Java. 

Here are couple of more examples, which is self explanatory.

java.lang.classcastexception java.util.arraylist cannot be cast to java.util.map
java.lang.classcastexception ljava.lang.object cannot be cast to ljava.lang.comparable
java.lang.classcastexception ljava.lang.object cannot be cast to ljava.lang.integer
java.lang.classcastexception ljava.lang.object cannot be cast to java.util.list
java.util.arraylist cannot be cast to java.lang.comparable

How to fix java.lang.ClassCastException in Java

Solving ClassCastException can be very easy once you
understand polymorphism in Java and difference
between compile time and runtime things.
ClassCastException are simple
like NullPointerException
just look the stack-trace and go to the line number. Many of advanced Java IDE
like Eclipse and Netbeans will give you
hyperlink to
navigate till culprit line number in Java file. 



Now you know where exactly ClassCastException
is coming and stack trace also told which object it was trying to cast,
Now you have to find, how that type of object comes and this could take some time
based upon complexity of your java application. You can also prevent ClassCastException
in Java by
using Generics. 



Generics are designed to write type-safe code and provides
compile-time checks which tends to violate type-safety. By using Generics in Collection
classes and other places you can safely minimize
java.lang.ClassCastException
in Java.

That’s all on What is ClassCastException in Java and how to solve Exception in thread “main” java.lang.ClassCastException. I highly
recommend to use Generics while using any Collection classes or class which
acts as container e.g. ThreadLocal
in Java. Also write your own classes and method to take advantage of
Generics to provide type-safety as shown in this example of How
to write parameterized class. It’s also a good idea to refresh your
knowledge on type-casting
in Java.

Other Java debugging and troubleshooting tutorials

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.

java lang ClassCastException

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.

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.

  1. ClassCastException(): It is used to create an instance of the ClassCastException class.
  2. 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

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. 

  1. public static String valueOf(boolean boolValue)
  2. public static String valueOf(char charValue)
  3. public static String valueOf(char[] charArrayValue)
  4. public static String valueOf(int intValue)
  5. public static String valueOf(long longValue)
  6. public static String valueOf(float floatValue)
  7. public static String valueOf(double doubleValue)
  8. 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 :

Compile time error occurrence when tried to convert parent object to child object

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.

  1. ClassCastException(): It is used to create an instance of the ClassCastException class.
  2. 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. 

  1. public static String valueOf(boolean boolValue)
  2. public static String valueOf(char charValue)
  3. public static String valueOf(char[] charArrayValue)
  4. public static String valueOf(int intValue)
  5. public static String valueOf(long longValue)
  6. public static String valueOf(float floatValue)
  7. public static String valueOf(double doubleValue)
  8. 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 :

Compile time error occurrence when tried to convert parent object to child object

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.

I read some articles written on «ClassCastException», but I couldn’t get a good idea on what it means. What is a ClassCastException?

Zoe stands with Ukraine's user avatar

asked May 25, 2009 at 16:45

Chathuranga Chandrasekara's user avatar

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

coobird's user avatar

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 {...}
  1. You can cast any of these things to Object, because all Java classes inherit from Object.
  2. You can cast either B or C to A, because they’re both «kinds of» A
  3. You can cast a reference to an A object to B only if the real object is a B.
  4. You can’t cast a B to a C even though they’re both A’s.

answered May 25, 2009 at 16:47

Charlie Martin's user avatar

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
 }

Kick Buttowski's user avatar

answered May 25, 2009 at 16:49

Yishai's user avatar

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:

  1. 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.
  2. 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

Kick Buttowski's user avatar

answered Apr 5, 2013 at 18:58

Elizabeth Courpalis's user avatar

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's user avatar

Neuron

4,8535 gold badges36 silver badges54 bronze badges

answered May 25, 2009 at 16:47

Mork0075's user avatar

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.

Community's user avatar

answered Oct 5, 2012 at 11:03

shakun tyagi's user avatar

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 Huiskamp's user avatar

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

Suganthan Madhavan Pillai's user avatar

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.

Peter Mortensen's user avatar

answered Apr 2, 2013 at 10:05

Mistriel's user avatar

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

Lalik's user avatar

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

Ananta Chandra Das's user avatar

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's user avatar

Sociopath

12.9k18 gold badges45 silver badges73 bronze badges

answered Sep 18, 2018 at 5:28

karepu's user avatar

karepukarepu

1861 silver badge6 bronze badges

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);

        }

    }

}

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

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.

If a ClassCastException is one of the most common exceptions in Java. It is a runtime exception that occurs when the application code attempts to cast an object to another class of which the original object is not an instance. For example, a String object cannot be cast to an Integer object and attempting to do so will result in a ClassCastException.

Since the ClassCastException is an unchecked exception, it doesn’t need to be declared in the throws clause of a method or constructor.

Sources of ClassCastException

Some of the most common sources of ClassCastException in Java are:

  • Using collections like HashMap, ArrayList and HashTable which do not use Java Generics.
  • Using methods which were written on interfaces prior to Java 5 that use polymorphism.
  • Not using type-safety when casting objects in Java.

ClassCastException Example

Here is an example of a ClassCastException thrown when a String is attempted to be cast to an Integer:

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

In this example, the String obj is attempted to be cast to an Integer. Since it is not an instance of the Integer class, this operation throws a ClassCastException:

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

How to Fix ClassCastException

To fix the ClassCastException in the above example, the object type should be checked before performing the cast operation:

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

The code is updated with a check that makes sure obj is an instance of the Integer class before it is cast to an Integer. The cast operation is only done if the check passes. The above code runs successfully without throwing a ClassCastException

Hello

How to Avoid ClassCastException

The ClassCastException can be avoided using checks and preventive techniques like the following:

  • When trying to cast an object to another class, make sure that the new type belongs to one of its parent classes. The instanceof operator in Java can be used to ensure this.
  • Using Generics, since they provide compile time checks and can be used to ensure type-safety.

Track, Analyze and Manage Java Errors With Rollbar

Rollbar in action

Managing 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 Java error monitoring and triaging, making fixing errors easier than ever. Try it today.

Добавить комментарий