Quick Answer
Handle invalid type casting.
Understanding the Issue
Occurs when trying to cast an object to a subclass of which it is not an instance. Always check with instanceof before casting.
The Problem
This code demonstrates the issue:
Java
Error
Object obj = "hello";
Integer num = (Integer) obj; // Throws
The Solution
Here's the corrected code:
Java
Fixed
// Safe casting
if (obj instanceof Integer) {
num = (Integer) obj;
} else {
// Handle incompatible type
}
// With pattern matching (Java 16+)
if (obj instanceof Integer i) {
System.out.println(i + 1);
}
Key Takeaways
Always verify types before casting.