Back to course

Introduction to Assertions (assert keyword)

Java Mastery: From Zero to Professional Developer (50-Lesson Journey)

Lesson 35: Introduction to Assertions (assert keyword)

Assertions are statements used to test assumptions about the internal state of a program. They are primarily used for debugging and development testing, not for handling expected runtime errors.

1. Assertion Syntax

Java has two forms of the assert statement:

Form 1: Simple Condition

java assert condition;

If condition evaluates to false, an AssertionError is thrown.

Form 2: Condition with Detail Message

java assert condition : "Detail message describing failure";

2. Example Usage

java public double calculateDiscount(int quantity) { // Assertion: We assume quantity should never be negative here. // If it is, this indicates a deep logic flaw we need to fix during development. assert quantity >= 0 : "Quantity cannot be negative: " + quantity;

if (quantity > 10) {
    return 0.20; 
} else {
    return 0.05;
}

}

3. Enabling Assertions

Assertions are disabled by default in Java for performance reasons. They must be explicitly enabled when running the JVM using the -ea (enable assertions) flag.

To run the code with assertions enabled:

bash java -ea YourClass

Important Distinction:

  • Exceptions are for recoverable, expected errors (e.g., file not found, bad user input).
  • Assertions are for internal logic errors that should never happen in a correctly running program. If an assertion fails, it means the code logic needs fixing, not just graceful handling.