Static typing checks declared and inferred expression types before execution, allowing the compiler to reject incompatible values. Casts can discard this protection: an object declared as Object may be forced into String and fail later with ClassCastException. section 5.3.1 section 5.5
A cast that weakens static checking
public void process(Object obj) { String str = (String) obj; … // Use str. } If the method really requires a String, declaring the parameter as String moves incompatibility detection to compilation. If Object is required by an interface, check with instanceof before casting and reject unexpected values explicitly. section 5.3.1 section 5.3.1
Prefer static type checking over avoidable casts:
- Use a more concrete variable, parameter, or return type when the value is known to have one. section 5.3.1
- Avoid unguarded casts; use pattern matching with instanceof to test and bind the target type together. section 5.3.1
- Avoid unchecked generic casts: type erasure can delay ClassCastException until an implicitly cast value is used. section 5.5
- Treat cast warnings as useful but potentially noisy; inspect the surrounding contract before applying a fix. section 5.3.1
if (obj instanceof MyType myType) {
… // Use myType.
}
Pattern matching combines the instanceof test and type binding, reducing repeated type names and copy-paste mistakes. section 5.3.1











