ClassCastException Example
Let’s see a simple example of how ClassCastException occurs.
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Animal();
Dog d = (Dog) a; // ClassCastException occurs here
d.bark();
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
Exception in thread "main" java.lang.ClassCastException: class Animal cannot be cast to class Dog
Explanation:
The object a is of type Animal, and we are trying to cast it to Dog. Since a was not originally a Dog, the program throws a ClassCastException.
How to Fix ClassCastException
To fix ClassCastException, ensure that the object being cast belongs to the correct class.
1. Use the instanceof Operator
Before casting an object, check its type using instanceof to avoid exceptions.
public class Main {
public static void main(String[] args) {
Animal a = new Animal();
if (a instanceof Dog) {
Dog d = (Dog) a;
d.bark();
} else {
System.out.println("Cannot cast Animal to Dog");
}
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
Cannot cast Animal to Dog
Explanation:
The instanceof check ensures that a is a Dog before casting, preventing ClassCastException.
Troubleshooting ClassCastException Errors
A ClassCastException is a runtime error that occurs when your code tries to cast an object to a type it doesn’t belong to. This usually happens when you’re working with inheritance or interfaces, and you mistakenly assume an object is of a certain type. Let’s understand this with an example.
Example Scenario
Imagine you have a class hierarchy where `Animal` is the parent class, and `Dog` and `Cat` are subclasses. This is how the classes might look:
class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Woof!");
}
}
class Cat extends Animal {
void meow() {
System.out.println("Meow!");
}
}

You can also try this code with Online Java Compiler
Run Code
Now, let’s say you create an `Animal` object and try to cast it to a `Dog`:
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal();
Dog myDog = (Dog) myAnimal; // This will throw a ClassCastException
myDog.bark();
}
}

You can also try this code with Online Java Compiler
Run Code
When you run this code, Java will throw a ClassCastException because `myAnimal` is an instance of `Animal`, not `Dog`. You can’t cast a parent class object to a subclass unless the object is actually an instance of that subclass.
Why Does This Happen?
The error occurs because Java enforces type safety at runtime. When you cast an object, Java checks if the object is actually an instance of the target class. If it’s not, the JVM throws a ClassCastException to prevent invalid operations.
How to Fix It
To avoid this error, you need to ensure that the object you’re casting is actually an instance of the target class. One way to do this is by using the `instanceof` operator. Let’s see how you can modify the code to prevent the exceptions:
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Dog(); // Now myAnimal is actually a Dog
if (myAnimal instanceof Dog) {
Dog myDog = (Dog) myAnimal;
myDog.bark();
} else {
System.out.println("This animal is not a dog.");
}
}
}

You can also try this code with Online Java Compiler
Run CodeIn this updated code, we first check if `myAnimal` is an instance of `Dog` using the `instanceof` operator. If it is, we safely cast it to `Dog` and call the `bark()` method. If not, we print a message to avoid the exception.
Key Takeaways
1. Check Before Casting: Always use `instanceof` to verify the object’s type before casting.
2. Understand Inheritance: Be clear about the class hierarchy and relationships between classes.
3. Debugging Tip: If you encounter a ClassCastException, trace the object’s type back to where it was created or assigned.
Common Error Messages
When a ClassCastException occurs, Java provides an error message that helps you identify the problem. These messages might look confusing at first, but they contain valuable information about what went wrong. Let’s discuss some common error messages and understand what they mean.
1. Basic ClassCastException Message
The most common error message looks like this:
Exception in thread "main" java.lang.ClassCastException: class Animal cannot be cast to class Dog (Animal and Dog are in unnamed module of loader 'app')
What Does This Mean?
- `Animal cannot be cast to Dog`: This part tells you that the code tried to cast an object of type `Animal` to type `Dog`, which is not allowed.
- `Animal and Dog are in unnamed module of loader 'app'`: This part provides additional context about where the classes are located. In most cases, you can ignore this unless you’re working with advanced module systems.
Example Code That Causes This Error:
class Animal {}
class Dog extends Animal {}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal();
Dog myDog = (Dog) myAnimal; // This will throw a ClassCastException
}
}
How to Fix It:
As discussed earlier, you should use the `instanceof` operator to check the object’s type before casting:
if (myAnimal instanceof Dog) {
Dog myDog = (Dog) myAnimal;
} else {
System.out.println("Cannot cast Animal to Dog.");
}
2. ClassCastException with Collections
Another common scenario involves collections, such as `ArrayList`. Here’s an example error message:
Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')
What Does This Mean?
- `Integer cannot be cast to String`: This means the code tried to cast an `Integer` object to a `String`, which is not allowed.
- `java.lang.Integer and java.lang.String are in module java.base`: This indicates that both classes are part of Java’s standard library.
Example Code That Causes This Error
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add(123); // Adding an Integer
String str = (String) list.get(0); // This will throw a ClassCastException
}
}
How to Fix It:
To avoid this, you should use generics to specify the type of objects the collection can hold:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Hello"); // Only Strings are allowed
String str = list.get(0); // No casting needed
}
}

You can also try this code with Online Java Compiler
Run Code3. ClassCastException with Interfaces
Sometimes, the error occurs when working with interfaces. Here’s an example error message:
Exception in thread "main" java.lang.ClassCastException: class Cat cannot be cast to class Runnable (Cat is in unnamed module of loader 'app'; Runnable is in module java.base of loader 'bootstrap')
What Does This Mean?
- `Cat cannot be cast to Runnable`: This means the code tried to cast a `Cat` object to the `Runnable` interface, which is not allowed unless `Cat` implements `Runnable`.
- `Cat is in unnamed module of loader 'app'`: This indicates that `Cat` is a custom class in your application.
Example Code That Causes This Error
class Cat {}
public class Main {
public static void main(String[] args) {
Cat myCat = new Cat();
Runnable runnable = (Runnable) myCat; // This will throw a ClassCastException
}
}

You can also try this code with Online Java Compiler
Run Code
How to Fix It:
To fix this, ensure that the class implements the required interface:
class Cat implements Runnable {
public void run() {
System.out.println("Cat is running!");
}
}
public class Main {
public static void main(String[] args) {
Cat myCat = new Cat();
Runnable runnable = myCat; // No casting needed
runnable.run();
}
}

You can also try this code with Online Java Compiler
Run CodeTroubleshooting Steps
When you encounter a ClassCastException, it’s important to follow a systematic approach to identify and fix the issue. Let’s take a look at some of the steps you can take to troubleshoot and resolve this error:
Step 1: Understand the Error Message
The first step is to carefully read the error message. It usually tells you which classes are involved in the invalid cast. For example:
java.lang.ClassCastException: class Animal cannot be cast to class Dog

You can also try this code with Online Java Compiler
Run Code
This message indicates that the code tried to cast an `Animal` object to a `Dog` object, which is not allowed unless the `Animal` object is actually a `Dog`.
Step 2: Trace the Object’s Origin
Next, trace back to where the object was created or assigned. This helps you understand why the object is of the wrong type. For example:
Animal myAnimal = new Animal();
Dog myDog = (Dog) myAnimal; // Error occurs here

You can also try this code with Online Java Compiler
Run Code
In this case, `myAnimal` is explicitly created as an `Animal`, so casting it to `Dog` is invalid. To fix this, ensure the object is of the correct type before casting.
Step 3: Use `instanceof` to Check the Object’s Type
Before performing a cast, always check the object’s type using the `instanceof` operator. This prevents the ClassCastException by ensuring the cast is valid. For example:
if (myAnimal instanceof Dog) {
Dog myDog = (Dog) myAnimal;
myDog.bark();
} else {
System.out.println("This animal is not a dog.");
}

You can also try this code with Online Java Compiler
Run Code
This code checks if `myAnimal` is an instance of `Dog` before casting it. If it’s not, it prints a message instead of throwing an exception.
Step 4: Review Class Hierarchies and Interfaces
If the error involves inheritance or interfaces, review the class hierarchy to ensure the cast makes sense. For example:
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}

You can also try this code with Online Java Compiler
Run Code
In this hierarchy, you can cast a `Dog` or `Cat` to `Animal`, but not the other way around unless the object is actually a `Dog` or `Cat`.
Step 5: Use Generics to Avoid Casting
If the error occurs with collections, use generics to specify the type of objects the collection can hold. This eliminates the need for casting. For example:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
String str = list.get(0); // No casting needed
}
}

You can also try this code with Online Java Compiler
Run Code
By using `ArrayList<String>`, you ensure that only `String` objects are added to the list, so no casting is required.
Step 6: Debugging with Print Statements
If you’re unsure why an object is of the wrong type, use print statements to debug. For example:
System.out.println("Object type: " + myAnimal.getClass().getName());
This prints the actual class of the object, helping you understand why the cast failed.
Step 7: Test with Sample Code
To test your understanding, let’s write a complete example that demonstrates how to avoid a ClassCastException:
class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Woof!");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Dog(); // Correctly creating a Dog object
if (myAnimal instanceof Dog) {
Dog myDog = (Dog) myAnimal;
myDog.bark(); // This will work
} else {
System.out.println("This animal is not a dog.");
}
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
Woof!

You can also try this code with Online Java Compiler
Run Code
In this example, `myAnimal` is actually a `Dog`, so the cast is valid, and the `bark()` method is called.
Step 8: Handle Edge Cases
Sometimes, the error occurs in edge cases, such as when working with third-party libraries or complex inheritance hierarchies. In such cases, carefully review the documentation and test your code with different inputs to ensure it behaves as expected.
How to Avoid ClassCastException
Here are some best practices to avoid ClassCastException:
Use Generics Properly: Using generics ensures type safety.
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
String str = list.get(0); // Safe casting
System.out.println(str);
}
}
- Avoid Unchecked Casts: Always ensure correct object type before casting.
- Follow Proper Object Hierarchy: Design class hierarchies in a way that avoids unnecessary type conversions.
- Use Try-Catch for Exception Handling: Handling exceptions properly can prevent program crashes.
Track, Analyze and Manage Java Errors with Rollbar
For efficient debugging and tracking of errors like ClassCastException, developers use tools like Rollbar. Rollbar provides real-time error monitoring, helping developers:
- Identify error sources
- Track user impact
- Get real-time notifications
- Improve debugging efficiency
Using Rollbar, you can integrate automatic exception tracking into your Java application, making debugging easier.
Frequently Asked Questions
What is ClassCastException in Java?
ClassCastException occurs when an object is cast to a class that it is not an instance of, causing a runtime error.
How to prevent ClassCastException?
Use instanceof before casting, apply generics correctly, and avoid unchecked type conversions.
Can ClassCastException be caught in Java?
Yes, you can use a try-catch block to handle ClassCastException and prevent program crashes.
Conclusion
In this article, we discussed Java Lang ClassCastException, which occurs when an object is inappropriately cast to a subclass it does not belong to. This runtime exception can be avoided using instanceof checks before casting or by ensuring proper type conversions. Understanding ClassCastException helps in writing robust Java programs and preventing unexpected crashes.