How to use assert statement in Java?
AssertionException. Assertion statements are used while testing programs but not in real time. It allows a programmer to detect if the desired things happen. Here are 2 prototypes of the assert statement.
Note that, you should use assert statements to check if desired things happen. It is not a good idea to use them as conditional statements as you do with if-else.. One more important thing is that you cannot handle the
AssertionExceptionusing try-catch block!
public static void main(String args)
// An AssertionException is thrown when i is 5
// because 5 is not greater than 5
// 10,9,8,7,6 are greater than 5, so they are printed
// You can also print a custom message along with
assert i>5:"i is "+i;
While executing the program, don't forget to enable assertion. Use the following command to execute programs that contain assert statements. Otherwise, assertions will not work i.e. program executes as if the assert statement line is not present.
java -ea AssertDemowhere
-eais a flag that enables assertion. If you love this post, please share it and feel free to drop a comment.