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.














