Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

How does the Java assert statement work, when is it enabled, and why should it never be used to validate method arguments in public APIs?

The statement assert condition : message; throws an AssertionError with that message when the condition is false. Assertions are disabled by default and only run when the JVM is started with -ea (or -enableassertions), which can be switched on for the whole application, a package or a single class. Because they are normally off in production, they must never validate the arguments of public methods; for that we use explicit checks such as Objects.requireNonNull or throwing IllegalArgumentException.

Why this question is asked

Many developers have seen the assert keyword but never used it, and some use it in exactly the wrong place. Interviewers ask about it because the answer shows whether we know the difference between checking our own assumptions and enforcing a contract with callers, and because the fact that assertions are switched off by default surprises people in production. In this answer, we will look at how the assert statement works, how to enable it, why it is the wrong tool for public argument checks, why assertion expressions must never have side effects, and where assertions genuinely help.

1How the assert Statement Works

An assertion is a statement of something we believe must be true at a point in the code. If it is not true, our understanding of the program is wrong, and we want to know immediately. Java's assert has two forms: assert condition; and assert condition : message;. When the condition is false, the JVM throws an AssertionError, which is an Error rather than an Exception, so ordinary catch (Exception e) blocks do not swallow it.

Java
int[] sorted = sort(input);
assert isSorted(sorted) : "sort produced unsorted output: " + Arrays.toString(sorted);
// Run with: java -ea App
// Exception in thread "main" java.lang.AssertionError: sort produced unsorted output: [3, 1, 2]
// Run with: java App
// nothing happens; the assert line is skipped

The message expression after the colon is only evaluated when the assertion fails, so building a long message there costs nothing in the normal case.

2Enabling Assertions

Assertions are disabled by default. The compiled class keeps the assert code, but at run time the JVM skips it unless we turn it on. We can enable them broadly or narrowly, and disable them for parts of the code again.

Shell
java -ea App // enable for all application classes
java -enableassertions App // the same, long form
java -ea:com.acme.billing... App // only this package and its subpackages (the three dots are literal)
java -ea:com.acme.billing.Ledger App // only one class
java -ea -da:com.acme.legacy... App // enable everywhere except one package
java -esa App // enable in JDK system classes too
Where assertions are on and off
Where the code runsAssertionsWhy
Plain java commandOffDisabled unless -ea is given
Maven Surefire or Gradle testsOnBoth enable assertions by default
IDE test runnersUsually onMost add -ea for tests; check your settings
Production JVM or containerOffAlmost nobody adds -ea there

Notice that the package form ends in three dots; that is the syntax for a package and everything under it. Most build tools turn assertions on in tests: Maven Surefire and Gradle's test task both enable them by default, which is useful and is also the source of a classic production surprise.

3Why assert Must Not Validate Public Arguments

A public method has a contract with its callers: if you pass a null customer, you get a clear error. That contract has to hold every time the code runs. An assertion only holds when someone remembered to start the JVM with -ea, which in production almost nobody does. So an argument check written with assert simply disappears in the place where it matters most.

Java
// Wrong: silently skipped in production
public void transfer(Account from, Account to, long cents) {
assert from != null : "from";
assert cents > 0 : "cents must be positive";
... // in production, a null or negative value flows on and fails later, far away
}
// Right: always enforced
public void transfer(Account from, Account to, long cents) {
Objects.requireNonNull(from, "from"); // NullPointerException: from
Objects.requireNonNull(to, "to");
if (cents <= 0) {
throw new IllegalArgumentException("cents must be positive, was " + cents);
}
...
}

There is a second reason. The exception type is part of the method's contract. Callers expect an IllegalArgumentException or NullPointerException for a bad argument, not an AssertionError, which signals a bug inside the library. Explicit checks give the right type, the right message, and they run always.

4Assertions Must Not Have Side Effects

Because the whole assert statement is skipped when assertions are off, any work done inside the condition is skipped too. If the condition changes state, the program behaves differently with and without -ea, which is the worst kind of bug: it passes every test and fails only in production.

Java
// Wrong: the item is only removed when assertions are enabled
assert queue.remove(item) : "item was not in the queue";
// Right: do the work, then assert on the result
boolean removed = queue.remove(item);
assert removed : "item was not in the queue";

So the rule is that an assertion only reads. It may call a pure method such as isSorted(), but never one that modifies, consumes, or advances anything.

5Where Assertions Are a Good Fit

Assertions are for things that can only be false if our own code is broken: internal invariants, post-conditions, and assumptions in private helpers. For example, a private method that is only ever called with a positive index, the balance of a ledger after an internal rebalancing step, or the branch of a switch we believe is unreachable. In development and tests they catch mistakes close to where they happen, and in production they cost nothing because they are skipped.

If a violated invariant would cause real damage in production, such as a wrong amount of money, then it is not a job for assert. It needs an explicit check that always runs and throws, as the follow-on question about payment calculations shows.

6Follow-up questions

Should we catch AssertionError?

Almost never. An AssertionError means our own code has a bug, and continuing in an unknown state is risky. Test frameworks are the main exception: JUnit's assertions throw AssertionError subclasses so the framework can report a failed test.

Can code tell whether assertions are enabled?

Yes, with a small trick: boolean enabled = false; assert enabled = true; leaves enabled true only when assertions are on. This is one of the very few places where a side effect in an assert is intentional, and it should be used rarely, for example to log a warning at startup.

Is Objects.requireNonNull slow compared to assert?

No. It is a null comparison and a method call that the JIT inlines, so its cost is negligible. Performance is not a reason to use assert for argument checks.

7Conclusion

In this answer, we saw that assert condition : message; throws AssertionError when the condition is false, but only when the JVM runs with -ea, which we can scope to a package or class. Because assertions are off by default and almost always off in production, they cannot enforce argument contracts, so public methods use Objects.requireNonNull and explicit IllegalArgumentException checks instead. Assertion expressions must not have side effects, since they are skipped when disabled. Assertions fit internal invariants and post-conditions that catch our own bugs during development and testing.

What to say in the interviewAbout 80 seconds aloud

Open with

The assert statement is assert condition, or assert condition colon message. If the condition is false, the JVM throws an AssertionError with that message. The important part is that assertions are disabled by default: they only run when the JVM is started with -ea or -enableassertions, which I can scope to a package with -ea:com.acme... or to one class, and disable selectively with -da.

Then, if they want more

Test runners like Maven Surefire and Gradle turn them on by default, but production JVMs almost never do. That is exactly why assert must not validate arguments of public methods. A public method's contract has to hold every time, and with assertions off a null or negative argument would just slip through and fail somewhere far away.

So for arguments I use Objects.requireNonNull and explicit checks that throw IllegalArgumentException, which also gives callers the exception type they expect. A second rule is that an assertion expression must have no side effects, because when assertions are disabled the whole expression is skipped, so something like assert queue.remove(item) would behave differently in production.

I use assertions for cheap internal invariants and post-conditions in private code, things that can only be false if my own code has a bug.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How does the Java assert statement work, when is it enabled, and why should it never be...": https://scrivio-interview-library.netlify.app/java/exceptions/db39ba6b27/