ClassCastException in Java

ClassCastException in Java is a unchecked exception that occurs when you try to cast an object to a type that it is not compatible with.

ClassCastException in Java
public class ClassCastExceptionExample {
    public static void main(String[] args) {
        try {
            // Creating an object of type String
            Object obj = "Hello, World!";

            // Attempting to cast String to Integer
            Integer num = (Integer) obj; // This line will throw ClassCastException
        } catch (ClassCastException e) {
            System.out.println("ClassCastException caught: " + e.getMessage());
        }
    }
}

Output

ClassCastException caught: java.lang.String cannot be cast to java.lang.Integer

How to avoid ClassCastException in Java ?

To avoid getting a ClassCastException in Java, you need to ensure that the cast you are performing is valid and that the objects being cast are compatible. Here are some approaches to prevent ClassCastException:

Use instanceof for Type Checking

Before performing a cast, use the instanceof operator to check whether the cast is valid. This helps you avoid casting to an incompatible type.

if (obj instanceof Integer) {
    Integer num = (Integer) obj; // Safe cast
    // Continue using 'num' safely
} else {
    // Handle the case where 'obj' is not an Integer
}

Generics

Use generics to ensure type safety and avoid unnecessary casting. Here’s an example that demonstrates how to use generics to ensure type safety and avoid unnecessary casting:

import java.util.ArrayList;
import java.util.List;

public class GenericsExample {
    public static void main(String[] args) {
        List<Integer> integerList = new ArrayList<>();
        integerList.add(10);
        integerList.add(20);
        
        int sum = sumList(integerList);
        System.out.println("Sum of integers: " + sum);
        
        List<Double> doubleList = new ArrayList<>();
        doubleList.add(3.14);
        doubleList.add(2.71);
        
        double average = averageList(doubleList);
        System.out.println("Average of doubles: " + average);
    }
    
    // Using generics to calculate the sum of a List of numbers
    public static <T extends Number> int sumList(List<T> list) {
        int sum = 0;
        for (T num : list) {
            sum += num.intValue();
        }
        return sum;
    }
    
    // Using generics to calculate the average of a List of numbers
    public static <T extends Number> double averageList(List<T> list) {
        double sum = 0.0;
        for (T num : list) {
            sum += num.doubleValue();
        }
        return sum / list.size();
    }
}

In this example:

  1. The sumList method calculates the sum of a list of numbers using generics. The <T extends Number> notation specifies that T can be any type that extends the Number class, which includes types like Integer, Double, etc.
  2. The averageList method calculates the average of a list of numbers using a similar approach.
  3. In the main method, we create List<Integer> and List<Double> instances and populate them with values.
  4. We call the sumList and averageList methods with the respective lists, and the generics allow us to work with different numeric types without the need for explicit casting.

Generics provide type safety and allow you to write more reusable and flexible code, avoiding the need for manual type casting while maintaining type correctness.

Conclusion: ClassCastException in Java

In this article, we explored ClassCastException in Java and discussed different ways to avoid ClassCastException in Java.

Read More : List of Unchecked Exception in Java

Leave a Reply

Your email address will not be published. Required fields are marked *