Assertion in JAVA

In java, assertion is used to test the block of code using assert keyword, which is containing boolean expression. Assertion can be enabled or disabled. If enabled, execution causes to evaluate the expression and code executes normally, if expression condition is passed. If the condition failed, an assertion error is thrown indicating test has been failed. If assertion is disabled, executing the assert does not have any impact on program execution flow.

Code Syntax : Following code block shows the basic syntax of assert keyword. Here, in first statement, expression is evaluated and AssertionError is thrown if evaluated value is false.

In case of second statement, first expression (expression 1) should be evaluated to boolean a boolean value and second expression (expression 2) can be evaluated to any value, which is used as detailed message, in case of assertion error.

assert expression;
assert expression 1 : expression 2;

To enable assertion while running java program, we can pass -enableassertions or -ea as command line argument. To disable, we can use -disableassertions or -da argument.

java -ea AssertTest //Assertion enabled execution of java program.

To enable assertion in eclipse IDE, navigate to Run > Run Configurations > select Arguments tab > add -ea runtime argument > click on Apply button as shown below.

enable assertion

An example of assert statement

Following example shows how to use assert in java. Here, we are checking for test variable is null or not. As we have initialized test variable with null, running the program will throw assertion error with detailed message as “Entered text is null!!” as shown below.

public class AssertExample 
 public static void main(String args[])
    String test = null;
    assert test != null : "Entered text is null!!";

Output of above code.

assertion error

In this article, we learned about assertion in java. Assertion is very useful feature to test and debug the code while developing java applications and it should not be used in production environment as it may degrade the application performance.

You may be interested in following articles