Assertions

Assertions

A school program needs reliable data and clear rules. An assertion checks an internal assumption when assertions are enabled. It is useful for diagnosing programmer errors rather than accepting untrusted student input.

  1. Understand

    An assertion checks an internal assumption when assertions are enabled.

  2. Apply

    Trace the Java example, predict its output and explain the result before running it.

  3. Avoid mistakes

    Assertions are disabled by default. Validation needed for correctness must not disappear when the program runs without -ea.

Assertions

In Java, assertions act as internal sanity checks for your code. They're used by developers to confirm that the program logic is behaving as expected. If an assertion fails, it typically means there’s a bug in your program — not just a bad input, but a flaw in the code's assumptions.

What is an Assertion?

An assertion is a statement in Java that enables you to test your assumptions about the program during runtime. Assertions should not replace exception handling. Instead, they serve as internal self-checks that help developers catch bugs early in the development phase.

Syntax of Assertions in Java

Java provides the assert keyword in two forms:

// First form
assert condition;

// Second form (with a message)
assert condition : expression;

If the condition evaluates to false, an AssertionError is thrown. The optional expression provides a custom message for debugging.

Simple Example of Java Assertion

public class AssertionDemo {
    public static void main(String[] args) {
        int age = -5;
        assert age >= 0 : "Age cannot be negative";
        System.out.println("Age is: " + age);
    }
}
Exception in thread "main" java.lang.AssertionError: Age cannot be negative

How to Enable Assertions

By default, assertions are disabled at runtime. To enable them, you need to pass the -ea (or -enableassertions) flag to the JVM:


java -ea AssertionDemo

Where Should You Use Assertions?

Assertions are best used for validating internal states that should never happen under correct program logic. Here are some common scenarios:

  • Checking that a variable is within an expected range
  • Verifying unreachable code blocks
  • Postconditions (e.g., method guarantees)

Do Not Use Assertions For

There are places where assertions should never be used:

  • Validating user input
  • Enforcing business rules
  • Replacing exception handling

For example, don’t use assertions like this:

// BAD practice
assert email != null : "User must provide an email";

This assumes the user never provides a null email, which is not safe in real-world applications.

Using Assertions in Methods

Example 1: Postconditions

public int divide(int a, int b) {
    assert b != 0 : "Divider must not be zero";
    return a / b;
}

Example 2: Loop Invariants

int[] numbers = {2, 4, 6, 8, 10};
for (int num : numbers) {
    assert num % 2 == 0 : "All numbers should be even";
}

AssertionError Explained

When an assertion fails, the JVM throws an java.lang.AssertionError. This error halts the execution of the current thread and provides insight into what assumption was violated.

Should You Catch AssertionError?

Technically, yes — but it's discouraged. Assertions are meant for developers, and once they fail, the program shouldn’t attempt to recover. If you find yourself writing try-catch around assertions, consider whether you should be using exceptions instead.

Enabling and Disabling Assertions Selectively

You can enable assertions for specific classes or packages:


java -ea:com.example... MyApp

Or disable them selectively:


java -da:com.example.MyClass MyApp

Final Thoughts

Assertions are powerful but sharp tools — meant to be wielded with intention. Use them to fortify your internal logic, not to validate user behavior. When used appropriately, they can catch bugs early and make your codebase more robust and expressive.

Quick Recap

  • Use assert to test developer assumptions
  • Enable with -ea and disable with -da
  • Don’t use assertions to validate user input
  • Only use them where logic should never fail

Important boundaries and mistakes

Assertions are disabled by default. Validation needed for correctness must not disappear when the program runs without -ea.

Try the school example

Before running this Java program, write down each line you expect to see. Identify the value, branch, object or exception responsible for each line. Then explain whether the following assumption is valid: Assertions are disabled by default.

Java 17 · Main.java · complete practice program

public class Main  {
  public static void main(String[] args)  {
    int marks = 72;
    assert marks >= 0 : "negative mark";
    System.out.println(marks);
  }
}

Now change one thing: Set marks to -1 and compare java Main with java -ea Main. Predict the new behavior before checking the worked variation.

Worked answer and reasoning

Java 17 · Main.java · source repeated for this answer

public class Main  {
  public static void main(String[] args)  {
    int marks = 72;
    assert marks >= 0 : "negative mark";
    System.out.println(marks);
  }
}

Expected output

72

An assertion checks an internal assumption when assertions are enabled. It is useful for diagnosing programmer errors rather than accepting untrusted student input.

Assertions are disabled by default. Validation needed for correctness must not disappear when the program runs without -ea.

Run with javac Main.java, then java Main. The declaration of Main names the class; main starts the example, and println writes a complete output line.

Worked variation: Set marks to -1 and compare java Main with java -ea Main. The first prints -1; the second raises AssertionError.

Check your understanding

For the complete practice program in this lesson, which output is expected on Java 17?
Choose one answer. You can try again.

Answer and explanation

72

An assertion checks an internal assumption when assertions are enabled. It is useful for diagnosing programmer errors rather than accepting untrusted student input. Assertions are disabled by default. Validation needed for correctness must not disappear when the program runs without -ea.

Check a common mistake

Should required user-input validation rely only on assert?
Choose one answer. You can try again.

Answer and explanation

No. Assertions may be disabled at runtime.

Assertions need to be enabled. Input type does not turn optional assertions into required validation.

What to remember

An assertion checks an internal assumption when assertions are enabled. It is useful for diagnosing programmer errors rather than accepting untrusted student input. Assertions are disabled by default. Validation needed for correctness must not disappear when the program runs without -ea.

Related explanations: Java Variables, Java If Statement - Syntax and Examples, Java Class - Blueprint of Objects, Exceptions in Java Introduction.

Supporting documentation: Official Java learning guide and Java 17 language specification.

Reaching the recap and completing the quizzes are separate milestones.

    Course overview →