Java
Assertions
Learn to use the assert keyword to verify assumptions in your code, catch bugs early, and write more reliable programs.
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
The assert Keyword: Visual Flow
Two Forms of Assert
Checks the condition. Throws a bare AssertionError if false.
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.
When to Use Assertions
How to Apply Assertions
Example 1: Simple Assertion
Example 2: Unreachable Code
Example 3: Class Invariant
Assertion Lifecycle
When NOT to Use Assertions
Common Mistakes
assert i++ > 0; changes behavior when assertions are disabled since i won't increment.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
Consider the following code snippet:
public String getDayType(int day) {
switch (day) {
case 1: case 2: case 3: case 4: case 5:
return "Weekday";
case 6: case 7:
return "Weekend";
default:
// What goes here?
}
}
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?