In Java, an assertion is a statement that allows you to test your assumptions about your code at runtime. Assertions are typically used for debugging purposes, to ensure that certain conditions are met and to detect incorrect assumptions about the state of your code.
The standard form of an assertion statement in Java is assert expression;
, where expression
is a boolean expression that is evaluated at runtime. If the expression evaluates to true
, the assertion is considered successful and execution continues. If the expression evaluates to false
, the assertion fails and an AssertionError
is thrown.
Here is an example of an assertion statement that checks that an integer variable is positive:
int x = 5; assert x > 0;Source:www.lautturi.com
In this example, the assertion statement assert x > 0;
checks that the value of x
is greater than zero. If x
is indeed greater than zero, the assertion is successful and execution continues. If x
is not greater than zero, the assertion fails and an AssertionError
is thrown.
Another form of assertion statement in Java is assert expression1 : expression2;
, where expression1
is a boolean expression and expression2
is an expression that is evaluated and used as the message for the AssertionError
if the assertion fails.
Here is an example of an assertion statement with a message:
int x = -5; assert x > 0 : "x should be positive, but it is " + x;
In this example, the assertion statement assert x > 0 : "x should be positive, but it is " + x;
checks that the value of x
is greater than zero. If x
is not greater than zero, the assertion fails and an AssertionError
is thrown with the message "x should be positive, but it is -5".
Note that assertions are disabled by default in Java. To enable assertions, you need to use the -enableassertions
or -ea
command-line flag when running your program.