Lesson · Assertions & Defensive Programming
Assertions: the check that switches off
16 min readAssertions & Defensive Programming
An assert statement looks like a safety net and runs zero times in production. Learn what assertions are for — internal assumptions — and which real checks must take their place at the edges of your code.
The check that switches itself off
This program passed thousands of test runs. In production the check inside it never runs at all:
int balance = -5; assert balance >= 0 : "balance went negative: " + balance; System.out.println("reached the end normally");
Predict: with balance = -5, java AssertionsDemo prints reached the end normally, while java -ea AssertionsDemo stops with AssertionError: balance went negative: -5. Same file, two different programs — the switch is off by default.
How the switch works
assert is a statement with two forms, and four commands decide whether it runs:
assert balance >= 0; // condition only assert balance >= 0 : "balance: " + balance; // condition + message
| Run with | What it does | When you use it |
|---|---|---|
| nothing (the default) | every assert is skipped — the condition, the message and any method call inside them never run | production runs |
-ea or -enableassertions | all assertions in all classes run | your local runs and the test suite |
-ea:com.example... | assertions run only for that package and below | checking one area at a time |
-da | assertions off again, after a broad -ea | quieting an area you do not want checked |
- With assertions on, a false condition throws
AssertionErrorand stops the program. - The message after the colon is only built when the check fails — that is why it can be an expensive sentence.
AssertionErroris anError, not anException: it marks a broken assumption in your code, and is not meant to be caught.- The compiled class keeps the assert as a guarded check: a hidden "are assertions on?" flag decides whether the condition runs.
Name what it is: assert is a development-time claim about your own code — "this situation cannot happen". The flag decides whether the claim gets verified.
What assertions are for
Assertions describe internal assumptions: facts your own code guarantees when it is correct. If one of them is false, the right response is not recovery — it is finding the bug:
| Say this with `assert` | Say this with a real check |
|---|---|
| a private helper received a value my own code controls | a public method received an argument from a caller |
| an invariant this class itself maintains | a business rule, like "the balance must cover the amount" |
| a branch that should be unreachable | a condition the real world can produce: file missing, network down |
| "if this is false, I have a bug to fix" | "if this is false, the caller or the world has a problem to report" |
- Private method preconditions: the argument contract only your class can see, like a helper that may only be called with a sorted list.
- Invariants after mutation: "this list is sorted", "balance never goes negative" — re-checked after every change while you develop.
- Postconditions of tricky algorithms: what must be true when the method returns.
- Can't-get-here points:
default: assert false : "unknown shape: " + shape;announces that the branch should never execute.
The dividing line: assertions report bugs in your code during development. Everything a caller or the outside world can trigger needs a check that survives -ea being off.
The trap: work hiding inside an assert
Because the whole line disappears when assertions are off, any work placed inside the condition disappears with it:
static int calls = 0; static boolean check() { calls++; return false; } public static void main(String[] args) { assert check() : "check failed"; System.out.println("check ran " + calls + " times"); }
- Run it normally: it prints
check ran 0 times— the method never ran. - Run it with
-ea: it stops withAssertionError: check failed— the method ran once, then the program died. - That is a behavior change between development and production, caused by the check itself.
- Never validate inside an assert:
assert validate(input);means the validation silently disappears in production. - Never rely on an assert for control flow: the program must be correct in both modes.
The rule of the trap: if a call must happen, it never belongs inside an assert — neither in the condition nor in the message.
Assert switch · the flag decides whether the check exists
pick an example, flip the switch> reached the end normally
The assert line was skipped: the condition never ran, and the message was never built.
Both runs were executed: without the flag the assert line does nothing, with -ea the JVM throws AssertionError and stops. There is no third mode.
The toolkit for checks that must always run
When a check has to run in every mode, Java hands you a small set of standard moves:
| Situation | The move | Example |
|---|---|---|
| A caller passed a value that breaks the contract | throw IllegalArgumentException | if (count < 0) throw new IllegalArgumentException("count: " + count); |
A caller passed null where null is not allowed | Objects.requireNonNull — it always runs and throws NullPointerException | this.name = Objects.requireNonNull(name, "name"); |
| The object is not in the right state for this call | throw IllegalStateException | if (closed) throw new IllegalStateException("already closed"); |
| The outside world failed | handle the exception: report, retry or substitute (earlier chapter) | catch (IOException e) { ... } |
| An internal assumption only my own code can break | assert | assert isSorted(list) : "list lost its order"; |
Two speeds of checking. Cheap, always-on checks at the doors (public methods); assertions for the private assumptions deep inside, where a failure means you have a bug to fix.
The defensive playbook
Deciding what protects you, in order:
- Ask who can trigger the bad state: a caller, the outside world, or my own code.
- Caller → validate at the public door:
IllegalArgumentException, orObjects.requireNonNullfor null. - Outside world → normal exception handling (retry, substitute, report). Never an assert.
- My own code →
assertthe invariant at the point where the assumption must hold. - Keep work out of asserts; a check that must always run is never an
assert. - Run your tests with
-ea— otherwise the internal claims are never verified.
Run with `-ea`, or the net has no net. A test suite that never enables assertions is testing a program with all its internal checks removed.
AssertionError is a development tool; -ea decides whether it exists
With assertions off (the default), every assert line is skipped — condition, message and any method call inside them never run. Use asserts only for internal assumptions that mean "there is a bug in this code". For everything a caller or the outside world can cause, use IllegalArgumentException, Objects.requireNonNull, IllegalStateException and ordinary exception handling. Always run your tests with -ea.
Interview angles
What does an assert statement do when the program runs without -ea?+
Nothing at all — the condition and the message are skipped, and any method call inside them never executes.
The compiled class still contains the check, guarded by a hidden "are assertions on?" flag that the JVM sets from the command line. With the flag off, the guard jumps over everything, so the assert is present in the bytecode but absent from the behavior.
Common misconception: That the assert still evaluates quietly and just ignores failures — it is not even evaluated.
Follow-up: Then why is assert validate(input); a bug?
When is an assert the right tool?+
For internal assumptions: private preconditions, invariants, postconditions and unreachable branches — things that, if false, mean a bug in this code.
The test is who can break it. Only your own code can break a private helper's precondition, so a development-time check is the honest tool, and a failure means find the bug, not recover.
default: assert false : "unknown shape: " + shape;
Common misconception: That asserts can replace argument validation — validation must run in production, and asserts do not.
Follow-up: Where does the replacement for a public argument check go?
How do you check that a public method's argument is non-null?+
Objects.requireNonNull(name, "name") — it always runs and throws NullPointerException with the argument's name in the message.
Null-checking conventions split cleanly: null arguments get NullPointerException (that is what requireNonNull produces), other wrong values get IllegalArgumentException. Both run with or without -ea.
Common misconception: That assert name != null; is enough — in production it checks nothing.
Follow-up: And if the value is non-null but out of range, say a negative count?
What is the danger of a side effect inside an assert condition?+
With -ea off it never happens: a validation is skipped, a counter never counts, a cache is never filled — the program behaves differently in development and production.
The principle: an assert must be safely deletable. If deleting the line changes what the program does, the line is not an assertion — it is hidden logic wearing an assert costume.
Common misconception: That assertions are free to hold anything, since they are "just checks".
Follow-up: Where does the validation call belong instead?
A library catches AssertionError, logs it and continues. What is wrong?+
An AssertionError marks a broken internal assumption: the state that follows is unknown. Continuing is guesswork, and catching it hides the bug the assert was built to expose.
AssertionError extends Error for exactly this reason: it is not a normal failure to handle, it is the program telling you it no longer knows its own state. The legitimate response is a top-level report and stop.
Common misconception: That AssertionError is just another exception and can be handled like one.
Follow-up: So what should the run do when -ea is off and the same bug happens?