01 / 21

Java
Assertions

Learn to use the assert keyword to verify assumptions in your code, catch bugs early, and write more reliable programs.

Java

What Is an Assertion?

An assertion is a statement in your code that declares something you believe must be true at that point during execution. If the condition is true, the program continues normally. If it is false, the program throws an AssertionError and halts.

Why Assertions Matter

✓ Catch Bugs Early
Assertions detect incorrect assumptions during development, long before they reach production.
✓ Document Intent
They serve as executable documentation: a reader sees exactly what the programmer expected to be true.
✓ Zero Cost in Production
Assertions can be disabled at runtime, so they add no performance overhead in deployed code.

The assert Keyword: Visual Flow

assert condition; condition? Continue true AssertionError false

Two Forms of Assert

Simple Form
assert age >= 0;

Checks the condition. Throws a bare AssertionError if false.

Detailed Form
assert age >= 0 : "Negative age";

Includes a detail message passed to AssertionError for debugging.

Assert vs. If-Throw

assert if-throw
Purpose Verify internal assumptions Validate external input
Can be disabled? Yes (at runtime) No (always runs)
Throws AssertionError IllegalArgumentException, etc.
Use in production? Usually disabled Always active
Best for Developer debugging User/API safety

Enabling Assertions at Runtime

By default, Java disables assertions at runtime. You must explicitly enable them using a command-line flag when running your program.

// Enable assertions for all classes java -ea MyProgram // Enable only for a specific package java -ea:com.myapp... MyProgram // Disable assertions (default behavior) java -da MyProgram

When to Use Assertions

1
Internal invariants: conditions that must hold at a specific point in the logic, such as a variable being non-null after initialization.
2
Control flow invariants: unreachable code paths, like the default case in a switch that should never execute.
3
Postconditions: verifying a method's result is correct before returning it.
4
Class invariants: verifying an object's state is consistent at the start and end of each public method.

How to Apply Assertions

1
Identify the assumption: What do you believe must be true at this point in your code?
2
Write the boolean expression: Translate your assumption into a condition that evaluates to true or false.
3
Add the assert statement: Place assert condition; or assert condition : "message"; at the appropriate location.
4
Run with -ea: Execute the program with assertions enabled to verify your assumptions hold.
5
Investigate failures: If an AssertionError is thrown, debug the logic that violated the assumption.

Example 1: Simple Assertion

public double calculateAverage(int[] scores) { assert scores != null : "Scores array is null"; assert scores.length > 0 : "Scores array is empty"; int sum = 0; for (int s : scores) { sum += s; } double avg = (double) sum / scores.length; // Postcondition: average should be in range assert avg >= 0 && avg <= 100 : "Average out of range: " + avg; return avg; }

Example 2: Unreachable Code

enum Season { SPRING, SUMMER, FALL, WINTER } public String getActivity(Season s) { switch (s) { case SPRING: return "Gardening"; case SUMMER: return "Swimming"; case FALL: return "Hiking"; case WINTER: return "Skiing"; default: assert false : "Unknown season: " + s; return "Unknown"; } }

Example 3: Class Invariant

public class BankAccount { private double balance; public void withdraw(double amount) { assert amount > 0 : "Amount must be positive"; assert balance >= amount : "Insufficient funds"; balance -= amount; // Class invariant: balance never negative assert balance >= 0 : "Balance went negative: " + balance; } }

Assertion Lifecycle

Write Code Add Assertions Test with -ea Pass? yes Deploy (-da) no Fix Bug

When NOT to Use Assertions

1
Validating public method arguments: Use exceptions instead. Assertions can be disabled, leaving your method unprotected.
2
Side effects: Never put code with side effects inside an assert. If disabled, that code won't run, changing behavior.
3
User-facing error handling: Assertions crash the program. Use try-catch for graceful error recovery.

Common Mistakes

✕ Side Effects in Assert
Placing code like assert i++ > 0; changes behavior when assertions are disabled since i won't increment.
✕ Validating User Input
Using assert to check user-supplied data is dangerous: disabled assertions mean no validation at all.
✕ Forgetting -ea
Running without the -ea flag means all assertions are silently skipped, giving a false sense of correctness.

Summary at a Glance

Concept Details
Syntax (simple) assert condition;
Syntax (detailed) assert condition : message;
Error thrown AssertionError
Enable flag -ea
Disable flag -da
Best use Internal invariants, postconditions, unreachable code
Do NOT use for Public input validation, side-effect code

Question 1 of 5

What happens when an assert statement's condition evaluates to false and assertions are enabled?

Question 2 of 5

Which command-line flag enables assertions when running a Java program?

Question 3 of 5

Why is it dangerous to use side effects inside an assert statement, such as assert list.remove(item);?

Question 4 of 5

A developer writes a public method that accepts a user-provided age value. Which approach is more appropriate for checking that age is non-negative?

Question 5 of 5

If the day parameter is guaranteed to be 1 through 7 by an earlier validation step, what is the best statement to place in the default case?