Assertions

An assertion is a check a program makes about itself, and it is disabled unless the JVM is started with -ea. That default is the whole design: an assertion costs nothing in production and catches a broken assumption in testing. A check of what a user typed is the other thing, and it belongs in an exception.

Off by default

The program below uses the side effect of an assertion to report whether assertions are enabled, then asserts a range and prints a line after it:

public class Assertions { public static void main(String[] args) { boolean enabled = false; assert enabled = true; System.out.println("assertions " + (enabled ? "enabled" : "disabled")); int speed = 50; assert speed >= 0 && speed <= 40 : "speed out of range: " + speed; System.out.println("after the check"); } }

javac -Xlint:all Assertions.java
java Assertions

assertions disabled
after the check

Neither check ran. The first assertion is the trick of the lesson: the assignment happens only if the assertion is enabled, so the word disabled is proof and not a guess. The second assertion would have failed, and the program continued to the last line because the check that would have stopped it was never compiled into a test.

With -ea

The same program with the flag:

java -ea Assertions
echo "status: $?"

assertions enabled
Exception in thread "main" java.lang.AssertionError: speed out of range: 50
at Assertions.main(Assertions.java:7)
status: 1

The first line says the flag worked, and the second is an AssertionError whose message is the one after the colon in the assert statement. The class of the error is not an exception: it extends Error, which is the next lesson, and it means a bug in the program rather than a condition of the input.

The flag has three forms: -ea for all classes, -ea:com.example... for a package and its subpackages, and -da to switch them off again. A test run uses -ea, and a production run usually does not.

An invariant and an exception

The two kinds of check sit in one class: the public method validates its argument with an exception, and the internal state is checked with an assertion. The program runs both, once with the flag and once without:

public class Invariant { static int balance = 100; public static void main(String[] args) { deposit(50); System.out.println("balance " + balance); try { lower(200); } catch (IllegalStateException e) { System.out.println("rejected: " + e.getMessage()); } balance = 100; try { corrupt(); System.out.println("no assertion without -ea"); } catch (AssertionError e) { System.out.println("assertion: " + e.getMessage()); } } static void deposit(int cents) { if (cents <= 0) { throw new IllegalArgumentException("deposit must be positive: " + cents); } balance += cents; assert balance >= 0 : "balance went negative: " + balance; } static void lower(int cents) { balance -= cents; if (balance < 0) { throw new IllegalStateException("balance " + balance + " after lowering by " + cents); } } static void corrupt() { balance = -1; assert balance >= 0 : "balance went negative: " + balance; } }

javac -Xlint:all Invariant.java
java Invariant

balance 150
rejected: balance -50 after lowering by 200
no assertion without -ea

The exception fires in both runs, because it is ordinary code. The assertion fires only with the flag, and the same three lines become these four:

java -ea Invariant

balance 150
rejected: balance -50 after lowering by 200
assertion: balance went negative: -1

The difference is the lesson. A broken internal invariant is a bug in the program, and it should stop a test run loudly; a user asking for the impossible is a condition the program must report to its caller in every run. An assertion around deposit("-5") would be no check at all in production, which is why the method throws instead.

What an assertion is for

Assert the invariants of the code itself: a precondition of a private method, a state that the class guarantees, a loop invariant, a case that the logic says cannot happen. Never assert a check of user input, a public parameter or anything a caller should be told about, because the message reaches nobody when the flag is off. And do not put work with a side effect inside an assertion unless the side effect is the test, as the first program does on purpose.

The cost of an assertion when it is on is one comparison and a branch, and the message is built only when the check fails. A JUnit run enables them, which is why a project's test task usually passes -ea; the test tool of lesson 127 comes later in the course.

Exercises

  1. Add an assertion that the balance is below a million after a deposit and watch it pass.
  2. Change corrupt to check a different invariant and print the message with the flag on.
  3. Run Assertions with -da -ea:Assertions and explain the two flags.
  4. Write a private method whose precondition is an assertion and call it with a value that breaks it under -ea.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. When does an assertion run?

    Answer

    Only when the JVM is started with -ea or another enabling flag

    The default is off, which is what makes an assertion free in production.

  2. What is thrown by a failed assertion?

    Answer

    AssertionError, which extends Error

    A broken assertion is a bug in the program, so the class sits under Error.

  3. Why is an assertion the wrong check for user input?

    Answer

    The check is absent when the flag is off, so nothing validates the input

    Validation has to run in every execution, and an assertion by design does not.

  4. What does this program print? public class Q1 { public static void main(String[] args) { int n = 5; assert n > 0; System.out.println("ok " + n); } }

    Answer

    ok 5

    Assertions are off by default, so the check is skipped and the line prints.

  5. What does assert x : "message"; print when it fails?

    Answer

    The message in the AssertionError

    The expression after the colon becomes the message of the error.

  6. Which run enables an assertion in the class Assertions?

    Answer

    java -ea Assertions

    The flag belongs to the java command, before the class name.

  7. Why is an assertion cheap when it is disabled?

    Answer

    The compiler writes no code for it, so nothing runs at all

    A disabled assertion is absent from the class file behaviour, which is why it is free.

  8. What does this program print? public class Q2 { static int value = 10; static void check() { assert value > 0 : "value is not positive"; } public static void main(String[] args) { check(); System.out.println("done " + value); } }

    Answer

    done 10

    Without -ea the assertion is absent, so the method returns and the line prints.

  9. What does this program print when it is run without the flag? public class Q3 { public static void main(String[] args) { int n = -1; assert n >= 0 : "negative " + n; System.out.println("after"); } }

    Answer

    after

    Assertions are off by default, so the check is skipped; with -ea the program would fail on the assertion.

  10. Which check belongs in an assertion?

    Answer

    A private method precondition that the class guarantees

    An invariant of the code is what the program controls, so a failed assertion is a bug.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev

Banner image