skip to content

What does Java's assert statement do, why is it off without -ea, how does it compile, and when should you use it over an exception?

level: middleimportance: should knowfreq 42%

answer

  1. a check you can switch off
  2. two forms, one optional detail
  3. default off, a launcher switch enables
  4. synthetic static final flag per class
  5. your own bugs versus public contracts

basics

~20 s

Java's assert throws AssertionError when its condition is false, but only if enabled; the default is off to avoid runtime cost, and -ea turns it on. javac guards it with a static flag. Use it for internal invariants, exceptions for public arguments.

solid answer

~40 s

`assert cond;` or `assert cond : detail;` (since 1.4) evaluates `cond` when assertions are enabled and throws `AssertionError` if it is false, with `detail` as the message. When disabled, neither expression is evaluated. Assertions are off by default so that checks, which can cost as much as the work they check, are no liability in deployment, and `-ea` turns them on without a rebuild. In JDK 27, `javac` emits `if (!$assertionsDisabled && !cond) throw new AssertionError(detail);`, where `$assertionsDisabled` is a synthetic `static final` set during class initialization from the top-level class's `desiredAssertionStatus()`. Use it for internal invariants and nonpublic preconditions. Public argument checks must always run and throw the documented exception, so use `IllegalArgumentException` or `Objects.requireNonNull`, and put no required work inside an assert.

code

java · 14 lines
java
public class AssertDemo {
    private static int halve(int even) {
        assert even % 2 == 0 : "expected an even number, got " + even;
        return even / 2;
    }

    public static void main(String[] args) {
        boolean enabled = false;
        assert enabled = true; // intentional side effect: runs only when assertions are on
        System.out.println("assertions enabled: " + enabled);
        System.out.println(halve(4));
        System.out.println(halve(3));
    }
}

go deeper

for a junior

Recall the two forms, that a false condition throws AssertionError, and that plain java runs with assertions off until -ea is passed.

for a middle

Explain the mechanics: javac guards each assert with a synthetic static final flag set from the top-level class's desiredAssertionStatus, and a disabled assert evaluates neither of its expressions.

for a senior

Show judgment on where it belongs: internal invariants, not public arguments or outside data; no required work in the condition; a failure treated as a bug rather than something to recover from. Know the bytecode stays and counts towards inlining size.

for a principal

Weigh whether a team runs with -ea outside testing: earlier failure and better diagnosis against the cost of expensive checks and of stopping on a broken invariant. Then set the rule for which checks are asserts and which must always run.

## What the statement does An **assertion** is a check written in the code that can be switched on or off when the program starts. The Java Language Specification (§14.10) gives two forms: - `assert condition;` - `assert condition : detail;` `condition` must have type `boolean` or `Boolean`, and `detail` may be any expression except a `void` call; both are compile-time rules. When an assertion is **enabled**: - `condition` is evaluated, and a `true` result ends the statement. - On `false`, `detail` is evaluated if present, and an `AssertionError` is thrown with it as the detail message. A `Throwable` detail also becomes the error's cause. - A null `Boolean` condition throws `NullPointerException` on unboxing, not `AssertionError`. When an assertion is **disabled**, neither expression is evaluated and the statement completes normally. `AssertionError` extends `Error`, not `Exception`, so `catch (Exception e)` does not catch it. The specification says it is intended never to be caught, though that is possible. ## Why it is off without -ea A check can cost as much as the work it checks: confirming that a method really found a list's minimum means scanning the list again. The JDK's *Programming With Assertions* guide says assertions "are disabled by default" so that they "are not a performance liability in deployed applications", and the specification describes the usual pattern: enabled during development and testing, disabled for deployment. They stay in the class file so they can be turned on in the field without a rebuild, which the guide's design FAQ calls a firm requirement. The `java` launcher's switches are: | Switch | Applies to | |---|---| | `-ea`, `-enableassertions` | All classes except system classes | | `-ea:com.example...` | That package and its subpackages | | `-ea:com.example.Foo` | That class | | `-esa`, `-enablesystemassertions` | System classes | | `-da`, `-dsa` | The same scopes as `-ea` and `-esa`, disabling | "Off without `-ea`" is the default rather than the whole story. `ClassLoader` offers `setDefaultAssertionStatus`, `setPackageAssertionStatus` and `setClassAssertionStatus`, which affect classes initialized afterwards. Once a top-level class's status is determined, no later than its own initialization or that of a nested class, it cannot change. ## How javac compiles it The specification names none of this. It is how `javac` translates the statement in JDK 27, in an internal compiler class called `Lower`, and the result is the same in JDK 25. Written as source, the output looks like this: ```java class Halver { // javac adds this as a synthetic field and sets it first in static initialization static final boolean $assertionsDisabled = !Halver.class.desiredAssertionStatus(); static int halve(int even) { // source: assert even % 2 == 0 : "odd: " + even; if (!$assertionsDisabled && !(even % 2 == 0)) { throw new AssertionError("odd: " + even); } return even / 2; } } ``` - **The flag** is added to each class that needs one. `javap -c -p` shows it. - **Its value** comes from `desiredAssertionStatus()` on the **top-level** class, even in a nested class, which is why a nested class shares its outer class's status. - **Interfaces** cannot hold a non-public field, so `javac` puts the flag in a synthetic helper class. - **Constant conditions** simplify: `assert true;` generates nothing, and `assert false;` drops the condition test. - **Cost when disabled:** a `getstatic` and a branch stay in the bytecode. The guide calls a disabled assert "essentially equivalent" to an empty statement. HotSpot's C2 compiler treats a `static final` field like this one as a constant and can drop the branch, although the bytecode still counts towards the method size it uses for inlining decisions. The flag also explains an odd rule. The specification says an `assert` executed before its class has completed initialization is enabled, for cases such as a superclass's static initializer calling into a subclass that is still waiting to initialize. Until the subclass's initializer starts, the flag holds its default `false`, meaning "not disabled", so the check runs even without `-ea`. Inside the class's own static initializer the flag is already set, so with `javac` an `assert` there follows the real status. ## When to use it, and when an exception | Situation | Use | Reason | |---|---|---| | Internal invariant, such as what a branch implies | `assert` | A failure means a bug in this code | | A point you believe is unreachable | `assert false;` or `throw new AssertionError(...)` | The `throw` fires whatever the switches, and satisfies the compiler | | Precondition of a nonpublic method | `assert` | The callers are your own code | | Postcondition or class invariant | `assert` | It checks your own work | | Argument of a public method | `IllegalArgumentException`, `Objects.requireNonNull` and similar | The check is part of the contract and must hold with assertions on or off | | Data from outside the program | An exception | A correct program can still receive bad data | Two hazards remain: - **Required work inside the condition.** `assert names.remove(null);` removes nothing when assertions are off. Make the call first, keep its result, and assert on that. - **The wrong error type.** A failed `assert` throws `AssertionError`, not the exception a public method documents. `Objects.requireNonNull` always runs and throws `NullPointerException`; its use as a fail-fast parameter check is a question of its own.

  • How can a Java class tell whether its own assertions are enabled?
    Write `boolean on = false; assert on = true;`. The assignment runs only when assertions are enabled, so `on` reports the status, and it is one of the rare deliberate side effects in an assert. The assertions guide uses this in a static initializer to refuse to run with assertions off. `Class.desiredAssertionStatus()` is not the tool for this: its Javadoc says it is not guaranteed to return the actual status.
  • Why does assert false; at the end of a non-void Java method still give a missing return error?
    The reachability rules say an `assert` statement can complete normally if it is reachable, because a disabled one does nothing. So the compiler sees the method falling off its end, and reports `missing return statement`. `throw new AssertionError(...)` cannot complete normally, so it compiles, and it fires whatever the switches. That makes it the better choice for a branch that must not be reached.
  • Does plain -ea turn on assertions inside the JDK's own classes?
    No. With no argument, `-ea` applies to all classes except system classes, the ones without a class loader. `-esa`, or `-enablesystemassertions`, covers those. A package or class argument, as in `-ea:java.util...`, does reach system classes, because only the no-argument form carves them out.

  • Assertions run by default, so an assert protects production callers.
  • An assert is the right way to validate the arguments of a public method.
  • Required work can go inside an assert, because its condition always runs.
  • AssertionError is a RuntimeException, so catch (Exception e) handles it.
  • javac removes assert statements from the class file unless it is given -ea.
  • Plain -ea also enables assertions inside the JDK's system classes.

assert statement
Java 1.4

Assumes Java 27; the statement dates from 1.4, and the javac translation described is the same at 25 but is not specified by the language.

context