Site hosted by Angelfire.com: Build your free website today!
 

Assert

The assertion statement has two forms. The first, simpler form is:

    assert Expression1 ;

where Expression1 is a boolean expression. When the system runs the assertion, it evaluates Expression1 and if it is false throws an AssertionError with no detail message.

The second form of the assertion statement is:

    assert Expression1 : Expression2 ;

where:

  • Expression1 is a boolean expression.

  • Expression2 is an expression that has a value.

A Simple Example

class X {
        Integer i;
        Integer j;

        public void test(int n1, int n2) {
                i = new Integer(n1);
                j = new Integer(n2);
                assert i.equals(j) : "i == j";
        }

        public static void main(String[] args) {
                X x = new X();
                x.test(23,45);
        }
}
$ javac -source 1.4 AssertTest.java
$ java -ea AssertTest
Exception in thread "main" java.lang.AssertionError: i == j
        at AssertTest.test(AssertTest.java:8)
        at AssertTest.main(AssertTest.java:13)

For more information see:http://java.sun.com/j2se/1.4/docs/guide/lang/assert.html.