liveBook · Manning

Static typing

As explained in 100 Java Mistakes and How to Avoid Them

A static type system determines and checks the types of program expressions before execution.

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

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains safer declarations, guarded casts, inspections, and generic type-erasure delays, but does not develop type-system internals.
Examples
Uses Object-to-String processing, equals implementation, generic iteration, and IntelliJ IDEA cast inspections as concrete cases.
What it assumes
Assumes familiarity with Java casts and method declarations while teaching safer type choices through concrete failure modes.
What you can do after
Apply it by choosing concrete types, guarding required casts, adopting pattern matching, and reviewing unchecked-cast warnings contextually.
How it connects
Connects static typing with casts, instanceof, pattern matching, generics, type erasure, ClassCastException, and method type contracts.

Also explained in

Compare how 12 books explain static typing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.