Assertions in java

The assert statement, introduced in J2SE 1.4, consists of a boolean expression the programmer believes to be true when it is executed. If it is not true, Java will throw an AssertionError exception. Assertions are useful in testing and debugging programs. The syntax for assert is

assert boolean expression;

If boolean expression evaluates to false, an AssertionError exception is thrown with no associated message. Alternatively, we can use the syntax

assert boolean expression : value expression;

where value expression is an expression that returns a value; the string equivalent of this value is output in the AssertionError message if boolean expression is false.

Assertions are typically used within a default else clause, within an if/else statement, or within a switch statement with no default case. For example, suppose TestAssert contains the following code fragment:

switch (x)
{
case 1:
System.out.println(''case 1");
break;
case 2:
System.out.println("case 2");
break;
default:
assert false : x; System.out.println("default"); break;
}
System.out.println("carry on");


We believe that x can take on only the values 1 or 2. Should x take on any other value, the assert will fail.

By default, the javac compiler runs in 1.3 compatibility mode, so the -source option should be used, as follows:

> javac -source 1.4 TestAssert.java

At runtime, assertion checking is disabled by default. So if x is equal to 3, say, we will get the following result:

> java TestAssert
default carry on

To enable runtime assertion checking, use the -ea option, as follows:

> java -ea TestAssert

Exception in thread "main" java.lang.AssertionError: 3
at TestAssert.main(TestAssert.java.12)

No comments:

Post a Comment