Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java ReferenceJava Reference1

Java Assertions
Internal Self-Checks



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:

Do Not Use Assertions For

There are places where assertions should never be used:

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

QUIZ

Question 1:What happens when the following code is run with assertions enabled?
public class TestAssertion {
    public static void main(String[] args) {
        int x = -1;
        assert x >= 0 : "Negative value not allowed";
        System.out.println("x is: " + x);
    }
}

Question 2:Assertions are a valid replacement for exception handling in Java.

Question 3:Where is it appropriate to use assertions in Java?

Question 4:How can you enable assertions in a specific class when running a Java program?

Question 5:The following is a good use of an assertion:
assert email != null : "User must provide an email";

Question 6:Which of the following are true about Java's assertion mechanism?



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M