ADS

How To Use Assert Statement In Java?

Using assert statement in Java for testing purposes How to use assert statement in Java?
assert is a simple keyword in Java that allows you to specify a condition, which when failed throw an 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.


assert condition;
assert condition:expression;

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 AssertionException using try-catch block!
 class AssertDemo
{
    public static void main(String args[])
    {
        for(int i=10;i>=0;i--)
        {
            // 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
            assert i>5;
          
            // You can also print a custom message along with
            // AssertionException
            /*
            assert i>5:"i is "+i;
            */
            System.out.println(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. aktivitas executes as if the assert statement line is not present.
java -ea AssertDemo
where -ea is a flag that enables assertion. If you love this post, please share it and feel free to drop a comment.

Subscribe to receive free email updates:

ADS