Java Assertion: The ‘assert’ Keyword Example

Java assert keyword is used to create assertions in Java that enable us to test the assumptions about our program. For example, an assertion may be to make sure that an employee’s age is a positive number and greater than 18.

Java assert statements contain a boolean expression that must be true when the assertion executes. If it is not true, the system will throw an AssertionError when the assertions have been enabled using the -ea flag.

Person person = new Person(1L, "Lokesh", 14);

assert person.age() >= 18 : "Age is less than 18";   //Runtime error "java.lang.AssertionError: Age is less than 18"

1. Java assert Syntax

The assertion statement will have either of below two forms:

assert expression1;

//or 

assert expression1 : expression2;

Here –

  • expression1 is a boolean expression that the system evaluates to be true for normal processing and if it is false throws an AssertionError with no detailed message.
  • expression2 is an expression that is a value. It cannot be an invocation of a method that is declared void. The system passes the value of expression2 to the appropriate AssertionError constructor, which uses the string representation of the value as the error’s detail message.

The second form of the assertion statement should be used in preference to the first only when the program has some additional information that might help diagnose the failure.

Like all uncaught exceptions, assertion failures are generally labeled in the stack trace with the file and line number from which they were thrown.

2. Java assert Example

The assert statement can help support in design-by-contract style of programming. It can be used to validate the pre-conditions, post-conditions, and other general assertions.

For example, for a Person record, we want to enforce the contract that the person’s age must be greater than 18.

record Person(Long id, String name, int age) {
}

public class AssertExample {
  public static void main(String[] args) {

    Person person = new Person(1L, "Lokesh", 40);

    //Passes successfully
    assert person.age() >= 18 : "Age is less than 18";
  }
}

This helps in conditions when the person’s age falls below the expectation.

Person person = new Person(1L, "Lokesh", 14);

//Fails with AssertionError
assert person.age() >= 18 : "Age is less than 18";

This fails with the configured message for easy debugging.

$ java -ea .\AssertExample.java

Exception in thread "main" java.lang.AssertionError: Age is less than 18
        at com.howtodoinjava.core.basic.AssertExample.main(AssertExample.java:14)

In the above example, look at the assertion error message. It prints ‘Age is less than 18‘ which tells the parameter value was tested and failed. It helps in debugging.

3. Enable and Disable Assertions

Assertions are disabled, by default.

Sometimes assertions may increase the execution overhead of the program. To ensure that assertions are not a performance liability in deployed applications, assertions can be enabled or disabled when the program is started. Once disabled, they are essentially equivalent to empty statements in semantics and performance.

  • To enable assertions at various granularities, use the -enableassertions, or -ea, switch.
  • To disable assertions at various granularities, use the -disableassertions, or -da, switch.

The granularities can be defined like below:

Granularity LevelCommand ExampleDescription
No argumentsjava -ea MainEnables assertions in all classes except system classes.
Package Namejava -ea:com.howtodoinjava.dao... MainEnables assertions in the named packages and any subpackages.
Unnamed Packages in the current working directoryjava -ea:... MainEnables assertions in the unnamed package in the current working directory.
Class Namejava -ea:com.howtodoinjava.dao.RolesDao MainEnables assertions in the named class only.
Mixed Modejava -ea:com.howtodoinjava.dao... -da:com.howtodoinjava.dao.RolesDao MainEnables assertions in package com.howtodoinjava.dao; but not in class com.howtodoinjava.dao.RolesDao.

4. When Not to Use Assertions?

Although assertions are helpful in asserting the assumptions, we should not use them blindly. For example:

  • Do not enable assertions in production code. They can impose a performance overhead due to additional runtime checks.
  • Assertions are not an alternative for proper error handling using try-catch blocks and validations using JSR-380 annotations.
  • Do not use assertions to check security-related assumptions, as these will be disabled in production.


5. Conclusion

The ‘assert’ keyword in Java is a valuable tool. By enabling assertions during development and testing, you can catch issues early, document assumptions, and create more robust and maintainable software.

We must use them judiciously and disable them in production code to ensure the application’s performance is not impacted.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode