liveBook · Manning

Assertion

As explained in 100 Java Mistakes and How to Avoid Them

An assert statement is a Java language statement that evaluates a boolean condition and raises an assertion failure when the condition is false and assertions are enabled.

An assertion checks a condition that should be true in a correctly written Java program. When assertions are enabled and the condition is false, execution fails near the unexpected state, making defects easier to locate. section 1.7

assert condition;
assert condition : explanation;

Use either form to check a condition; the second form adds diagnostic context to the failure. section 1.7

Assertions are disabled by default and are commonly enabled during testing or staging with the JVM option -ea. Code must not depend on an assertion expression being evaluated in production. section 1.7 section 10.1

Avoid these assertion mistakes:

  • Keep side effects outside the assertion. With assertions disabled, expressions such as assert set.add(value) are skipped entirely; compute the result first, then assert it. section 10.1 section 10.8
  • Use assertions for invariants, not required input conditions. Replace a failed precondition such as missing input data with explicit validation and an appropriate exception. section 10.1
  • Treat static-analysis warnings as useful but incomplete: IDE inspections may flag assertion side effects, while method-level effects can be difficult to determine reliably. section 10.1 section 6.8

Separate the operation from the check

Instead of embedding mutation in an assertion, write boolean added = set.add(value); followed by assert added : "set already contains " + value;. The set is updated regardless of assertion status, while the assertion still detects the unexpected duplicate during enabled runs.

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains syntax, JVM enablement, side effects, preconditions, and analysis limits, but stops short of broader assertion design.
Examples
Uses set mutation, matcher processing, prefix normalization, and collection removal to expose assertion misuse and safer alternatives.
What it assumes
Assumes Java statement and JVM knowledge while teaching assertion syntax, enablement, invariant checks, and disabled-assert behavior.
What you can do after
Apply assertions safely by separating side effects, enabling them in tests, and replacing failed preconditions with explicit validation.
How it connects
Connects assertions with unit testing, invariants, preconditions, defensive programming, and static analysis.

Also explained in

Compare how 15 books explain assertion →

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.