Introduction
ClassCastException
in Java is a runtime exception that occurs when an object is cast to a class of which it is not an instance. This helps identify type mismatch errors in your code.
Table of Contents
- What is
ClassCastException
? - Common Causes
- Handling
ClassCastException
- Examples of
ClassCastException
- Conclusion
1. What is ClassCastException?
ClassCastException
is thrown when an object is forcibly cast to a class it does not belong to, indicating a type mismatch.
2. Common Causes
- Incorrect casting between unrelated classes.
- Casting without proper checks using
instanceof
.
3. Handling ClassCastException
To handle ClassCastException
, use a try-catch block and ensure proper type checking with instanceof
before casting.
4. Examples of ClassCastException
Example 1: Incorrect Casting
This example demonstrates handling a ClassCastException
when casting an object to an incompatible type.
public class IncorrectCastingExample { public static void main(String[] args) { Object obj = "Hello"; try { Integer num = (Integer) obj; // Incorrect casting } catch (ClassCastException e) { System.out.println("Error: Cannot cast String to Integer."); } } }
Output:
Error: Cannot cast String to Integer.
Example 2: Safe Casting with instanceof
This example shows how to safely cast an object using instanceof
to avoid ClassCastException
.
public class SafeCastingExample { public static void main(String[] args) { Object obj = "Hello"; if (obj instanceof String) { String str = (String) obj; // Safe casting System.out.println("String value: " + str); } else { System.out.println("Object is not a String."); } } }
Output:
String value: Hello
Conclusion
ClassCastException
is an important mechanism in Java for identifying type mismatch errors during casting. By properly handling this exception and using type checks, you can ensure type safety in your applications, leading to more robust and reliable code.