Java Assertions: Using assert, Enabling Assertions and Design by Contract
Learn Java assertions: the two forms of the assert statement, enabling them with -ea and -da per class or package, why conditions must have no side effects, when to assert versus throw, preconditions, documenting assumptions, and the ClassLoader assertion API.
kvi5hnuCode Sprout team member11 min readOn this page
Exceptions handle problems a program is expected to face: missing files, bad input, broken connections. But there's another category: things you are sure can't happen, because your own code guarantees them. A value that can't be negative. A branch that can't be reached. You'd still like to double-check those beliefs while developing, without paying for the checks in production. That's what assertions are for, a classic tool of defensive programming.
The idea behind assertions
Suppose you compute
double y = Math.sqrt(x);
and you are convinced that x isn't negative. Maybe it's the result of a computation that can't produce a negative value, or a parameter that callers are required to keep positive. Still, if you're wrong, sqrt quietly returns "not a number" (NaN), and garbage spreads through later calculations. You could add a check:
if (x < 0) throw new IllegalArgumentException("x < 0");
But that check stays in the program forever, even after testing is complete. Add hundreds of checks like it, and the program pays for all of them on every call.
Assertions let you put checks in during testing and have them switched off in production with no cost.
The assert statement
The assert keyword has two forms:
assert condition;
assert condition : expression;
Both evaluate the condition, and if it is false, throw an AssertionError. In the second form, the expression is passed to the AssertionError constructor and turned into the message string.
To assert that x is non-negative:
assert x >= 0;
Or include the actual value of x in the error, so you can see it when the assertion fails:
assert x >= 0 : x;
The expression part exists only to produce a message. AssertionError doesn't store the original value, so code can't query it later. The JDK designers made this choice on purpose: being able to inspect the value "would encourage programmers to attempt to recover from assertion failure, which defeats the purpose of the facility."
Enabling and disabling assertions
Assertions are disabled by default. Turn them on with the -enableassertions or -ea option:
java -enableassertions MyApp
You don't recompile to switch assertions on or off. Each class's assertion status is decided by the class loader when it loads the class. With assertions disabled, the assertion code is never executed, and the JIT compiler removes it, so it doesn't slow the program down.
You can be selective:
java -ea:MyClass -ea:com.mycompany.mylib... MyApp
This enables assertions in the class MyClass and in all classes of the package com.mycompany.mylib and its subpackages (that's what the three dots mean). -ea:... alone refers to the unnamed package.
To disable assertions for particular classes or packages, use -disableassertions or -da:
java -ea:... -da:MyClass MyApp

Some classes, the core JDK "system classes", aren't loaded by a class loader but directly by the virtual machine. The global -ea and -da switches don't apply to them. Use -enablesystemassertions (-esa) to turn on assertions in system classes, which is mainly useful for JDK developers.
Checking whether assertions are enabled
The -ea flag is invisible inside your code, but a small trick reveals it:
boolean enabled = false;
assert enabled = true; // a deliberate side effect: runs only when assertions are on
Class.desiredAssertionStatus() tells you what status a class would get if it were initialized now.
Assertion conditions must not have side effects
When assertions are off, the condition isn't evaluated at all. So never put code with a needed side effect in an assertion:
File file = new File(filename);
. . .
assert file.delete(); // BAD
The intent is to check that delete returns true. But with assertions off, which is how production runs, the file is never deleted! Move the work out of the assertion:
boolean deletionSuccessful = file.delete();
assert deletionSuccessful;
The trick above for detecting whether assertions are enabled is the one deliberate exception to this rule.
When to use assertions, and when not to
Java offers three mechanisms for dealing with failures: throwing exceptions, logging, and assertions. Assertions fit a narrow role:
- Assertion failures are meant to be fatal, unrecoverable errors.
- Assertion checks run only during development and testing. People jokingly compare this to wearing a life jacket near the shore and throwing it overboard once you're in the middle of the ocean.
So never use assertions to signal recoverable conditions to another part of the program, or to tell users about a problem. Use them only to find internal programming errors during testing.
| Use | For |
|---|---|
| Exceptions | Conditions callers can trigger or handle: invalid public arguments, missing files, network errors. Always on |
| Assertions | Your own internal assumptions: invariants, postconditions, "can't happen" branches, private-method preconditions. On only with -ea |
| Logging | Recording what happened, for diagnosis over the program's whole lifetime |
Assertions and parameter checking
Should you use assertions to check for an illegal index or a null reference? The answer is in the method's documentation. Suppose you implement:
/**
* Sorts the specified range of the specified array in ascending numerical order.
* The range to be sorted extends from fromIndex, inclusive, to toIndex, exclusive.
* @param a the array to be sorted
* @param fromIndex the index of the first element (inclusive) to be sorted
* @param toIndex the index of the last element (exclusive) to be sorted
* @throws IllegalArgumentException if fromIndex > toIndex
* @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length
*/
static void sort(int[] a, int fromIndex, int toIndex)
The documentation promises exceptions for bad indexes. That's part of the method's contract with its callers, so you must throw those exceptions. Assertions would be wrong: they'd disappear in production.
What about asserting that a isn't null? Also inappropriate as written. The documentation says nothing about null, so callers may reasonably expect a well-defined outcome, not an AssertionError.
Now change the contract slightly:
@param a the array to be sorted (must not be null)
Callers have been warned that null is illegal. Now the method may begin with
assert a != null;
This kind of requirement is called a precondition. The original method had no preconditions: it promised defined behavior in all cases. The revised method has one: a must not be null. If the caller violates a precondition, all bets are off, and the method may do anything at all. With the assertion in place, it does exactly that: it throws an AssertionError or a NullPointerException, depending on how the class loader is configured.
Assertions for documenting assumptions
Programmers often write their assumptions as comments:
if (i % 3 == 0)
. . .
else if (i % 3 == 1)
. . .
else // (i % 3 == 2)
. . .
An assertion is better: a comment is never checked.
if (i % 3 == 0)
. . .
else if (i % 3 == 1)
. . .
else {
assert i % 3 == 2;
. . .
}
Even better, think the problem through. What values can i % 3 have? For non-negative i: 0, 1 or 2. For negative i, Java's % can also give −1 or −2. So the real assumption is that i isn't negative, and the best assertion goes before the if:
assert i >= 0;
This shows assertions at their best, as a self-check for the programmer.
Assertions are a tactical tool for testing and debugging. Logging, the subject of the next article, is a strategic tool for the program's entire lifetime.
Controlling assertions from code
The ClassLoader class lets a program set assertion status for the classes it will load. These settings only affect classes loaded afterwards. A class that is already initialized keeps its status.
Method of java.lang.ClassLoader | Effect |
|---|---|
void setDefaultAssertionStatus(boolean b) | Enables or disables assertions for all classes loaded by this loader that don't have an explicit class or package setting |
void setClassAssertionStatus(String className, boolean b) | Enables or disables assertions for the given class and its inner classes |
void setPackageAssertionStatus(String packageName, boolean b) | Enables or disables assertions for all classes in the package and its subpackages |
void clearAssertionStatus() | Removes all explicit class and package settings and disables assertions for classes this loader loads |
The demo below uses setClassAssertionStatus to enable assertions for one class before it loads. That way you see real assertion failures even though the program runs without -ea.
A complete example
import java.util.*;
public class Solution {
static int sideEffects = 0;
public static void main(String[] args) {
// 1. are assertions on for this class? (run without -ea: no)
boolean enabled = false;
assert enabled = true; // intentional side effect: only runs when assertions are on
System.out.println("assertions enabled in Solution: " + enabled);
// 2. a disabled assertion isn't evaluated at all, so side effects vanish
assert ++sideEffects > 0;
System.out.println("side effects: " + sideEffects);
// 3. turn assertions on for one class before it is loaded
ClassLoader.getSystemClassLoader().setClassAssertionStatus("Geometry", true);
System.out.println("hypotenuse = " + Geometry.hypotenuse(3, 4));
try {
Geometry.sqrtOfDifference(4, 9);
} catch (AssertionError e) {
System.out.println("AssertionError: " + e.getMessage());
}
// 4. assertions as documented assumptions
for (int i : new int[] { 7, 8, 9 }) System.out.println(i + " -> " + Geometry.bucket(i));
try {
Geometry.bucket(-4);
} catch (AssertionError e) {
System.out.println("AssertionError: " + e.getMessage());
}
// 5. public contract: exceptions, always on, regardless of -ea
try {
Geometry.sort(new int[] { 3, 1, 2 }, 2, 1);
} catch (IllegalArgumentException e) {
System.out.println("IllegalArgumentException: " + e.getMessage());
}
// 6. an "unreachable" branch: throw an AssertionError explicitly, always active
System.out.println(Geometry.describe(Geometry.Shape.SQUARE));
}
}
class Geometry {
enum Shape { CIRCLE, SQUARE }
static double hypotenuse(double a, double b) {
double sumOfSquares = a * a + b * b;
assert sumOfSquares >= 0 : sumOfSquares;
return Math.sqrt(sumOfSquares);
}
static double sqrtOfDifference(double a, double b) {
double x = a - b;
assert x >= 0 : "x >= 0 failed, x = " + x; // the message is only built if the check fails
return Math.sqrt(x);
}
static String bucket(int i) {
assert i >= 0 : "negative input " + i; // the real assumption behind the branches below
if (i % 3 == 0) return "first";
else if (i % 3 == 1) return "second";
else {
assert i % 3 == 2;
return "third";
}
}
/** @throws IllegalArgumentException if fromIndex > toIndex */
static void sort(int[] a, int fromIndex, int toIndex) {
if (fromIndex > toIndex)
throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");
Objects.checkFromToIndex(fromIndex, toIndex, a.length);
Arrays.sort(a, fromIndex, toIndex);
}
static String describe(Shape s) {
switch (s) {
case CIRCLE: return "round";
case SQUARE: return "four equal sides";
}
throw new AssertionError("unknown shape " + s); // can't happen today
}
}
assertions enabled in Solution: false
side effects: 0
hypotenuse = 5.0
AssertionError: x >= 0 failed, x = -5.0
7 -> second
8 -> third
9 -> first
AssertionError: negative input -4
IllegalArgumentException: fromIndex(2) > toIndex(1)
four equal sides
Notice the first two lines: run without -ea, the assertions in Solution did nothing, not even their side effects. Geometry was loaded after its status was set, so its assertions are live. The sort method's argument check works the same with or without -ea, because it's an exception, not an assertion.
Common questions
Why are assertions disabled by default?
So that production code pays nothing for them and their behaviour doesn't change silently in deployed systems. Enable them with -ea during development and testing. Test frameworks run by Maven and Gradle enable them automatically.
Should I use assert to check method arguments?
Not in public methods. Callers you don't control can pass bad arguments in production, where assertions are off. Throw IllegalArgumentException or NullPointerException there. Assertions suit preconditions of private methods, postconditions and internal invariants.
Is AssertionError an exception I should catch?
No. It's an Error that signals a bug in your own code. Catching it to recover defeats the purpose. Let it fail the test or the program, and fix the code.
Are assertions used in modern Java code?
Less often than in the past. Many teams rely on unit tests and always-on checks (Objects.requireNonNull, Preconditions in libraries). The JDK itself still uses assert internally. For "impossible" branches, throw new AssertionError(...) is common because it's always active.
Can I enable assertions for just one package?
Yes. java -ea:com.example.billing... MyApp enables them for that package and its subpackages, and -da: disables them selectively. The most specific switch wins: a class switch beats a package switch, and a subpackage beats its parent, whatever their order on the command line. Order matters only when two switches name the same class or package; then the last one wins.
Summary
assert condition;andassert condition : message;throwAssertionErrorwhen the condition is false and assertions are enabled.- Assertions are disabled by default. Enable them with
-ea(optionally-ea:Classor-ea:package...), disable selectively with-da, and use-esafor system classes. No recompilation needed. - Disabled assertions aren't evaluated, so conditions must have no side effects.
- Use assertions for internal assumptions during development: invariants, postconditions, private preconditions, impossible branches.
- Don't use assertions for public argument checks, recoverable conditions or user-facing errors. Use exceptions.
throw new AssertionError(...)is an always-on check for code that must never be reached.ClassLoader.setClassAssertionStatusand related methods control assertion status from code, for classes not yet loaded.
Practice Questions
What is the difference between assert x > 0; and assert x > 0 : x;?
Both throw AssertionError if x > 0 is false and assertions are enabled. The second passes x to the error, so its value appears in the message.
You run java -ea -da.example.util... App. Where are assertions active?
In all application classes except those in com.example.util and its subpackages. System classes are not affected; they'd need -esa.
What is wrong with assert list.remove(item);?
With assertions disabled, which is the usual production setting, remove is never called, so the program behaves differently. Do the work first: boolean removed = list.remove(item); assert removed;.
A public method's Javadoc says it throws IllegalArgumentException for a negative count. May you check this with an assert instead?
No. The exception is part of the public contract and must happen even when assertions are disabled. Throw IllegalArgumentException explicitly.
In the i % 3 example, why is assert i >= 0; better than assert i % 3 == 2; in the last branch?
It states the real assumption. For negative i, i % 3 can be −1 or −2, so the branch logic is only correct for non-negative values. Checking i >= 0 up front catches the actual cause.
Why might someone write throw new AssertionError() at the end of a method instead of an assert statement?
It is always active, regardless of -ea, and the compiler treats it as the end of the method, so no dummy return value is needed. It documents that the code is believed to be unreachable.
You call ClassLoader.getSystemClassLoader().setClassAssertionStatus("Foo", true) after Foo has already been used. Do Foo's assertions now run?
No. Assertion status is fixed when the class is initialized. The setting affects only classes loaded afterwards.
Previous: Java Exception Handling Best Practices: Tips Every Developer Should Know
Next: Java Logging Basics: System.Logger and java.util.logging
Related reading
- Java Exception Handling Best Practices: Tips Every Developer Should Know
- Java finally and try-with-resources: Cleaning Up and Reading Stack Traces
- Catching Exceptions in Java: try/catch, Multi-catch, Rethrowing and Chaining
- Throwing Exceptions and Creating Custom Exception Classes in Java
- Java Exceptions: The Exception Hierarchy, Checked and Unchecked

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.