Wednesday, January 8, 2014

Assertions in Java


Assertions, introduced in Java 1.4, remain one of the most useful and important additions to the Java language. Assertions are used to codify the requirements that render a program correct or not. Assertions test conditions (aka Boolean expressions) for true values, notifying the developer when such conditions are false. Using assertions can greatly increase your confidence in the correctness of your code.
Assertions are compilable entities that execute at runtime, assuming you’ve enabled them for program testing. You can program assertions to notify you of bugs at the points where the bugs occur, which can greatly reduce the amount of time you would otherwise spend debugging a failing program.

Implementing Assertion
Assertions are implemented via the assert statement and java.lang.AssertionError class. This statement begins with the keyword assert and continues with a Boolean expression. An assert statement is expressed syntactically as follows: assert BooleanExpr;

If BooleanExpr evaluates to true, nothing happens and execution continues. If the expression evaluates to false, however, AssertionError is instantiated and thrown, as demonstrated in the following code:
public class AssertDemo
{
   public static void main(String[] args)
   {
      int x = -1;
      assert x >= 0;
   }
}
The assertion in AssertDemo indicates the developer’s belief that variable x contains a value that is greater than or equal to 0. However, this is clearly not the case; the assert statement’s execution results in a thrown AssertionError. Compile Listing 1 (javac AssertDemo.java) and run it with assertions enabled (java -ea AssertDemo). You should observe the following output:

Exception in thread “main” java.lang.AssertionError at AssertDemo.main(AssertDemo.java:6)


This message is somewhat cryptic in that it doesn’t identify what caused the AssertionError to be thrown. If you want a more informative message, use the assert statement expressed below: assert BooleanExpr : expr; Here, expr is any expression (including a method invocation) that can return a value—you cannot invoke a method with a void return type. A useful expression is a string literal that describes the reason for failure, as demonstrated in AssertDemo1.
public class AssertDemo1
{
   public static void main(String[] args)
   {
      int x = -1;
      assert x >= 0: “x < 0”;
   }
}
Compile AssertDemo1 (javac AssertDemo1.java) and run it with assertions enabled (java -ea AssertDemo1). This time, you should observe the following slightly expanded output, which includes the reason for the thrown AssertionError:

Exception in thread “main” java.lang.AssertionError: x < 0 at AssertDemo1.main(AssertDemo1.java:6)

Enabling Assertion on eclipse
If you are using eclipse then you will have to enable assertion on eclipse. For that please refer this Link.
Enjoy

2 comments: