Assertions

Objective

Notes

Assertion with no expression

public class Assert1 {
    public static void main(String[] args) {
        display("This is a test of the assertion mechanism");
        display(null);
    }
    
    private static void display(String msg) {
        assert msg != null;
        System.out.println(msg);
    }
}

/*

Sample output:

C:\>javac Assert1.java

C:\>java Assert1
This is a test of the assertion mechanism
null

C:\>java -ea Assert1
This is a test of the assertion mechanism
Exception in thread "main" java.lang.AssertionError
        at Assert1.display(Assert1.java:8)
        at Assert1.main(Assert1.java:4)

C:\>java -enableassertions Assert1
This is a test of the assertion mechanism
Exception in thread "main" java.lang.AssertionError
        at Assert1.display(Assert1.java:8)
        at Assert1.main(Assert1.java:4)
*/

Assertion including an expression

public class Assert2 {
    public static void main(String[] args) {
        display("This is a test of the assertion mechanism");
        display(null);
    }
    
    private static void display(String msg) {
        assert msg != null : "Message to display(String) was null";
        System.out.println(msg);
    }
}

/*

Sample output:

C:\>javac Assert2.java

C:\>java Assert2
This is a test of the assertion mechanism
null

C:\>java -ea Assert2
This is a test of the assertion mechanism
Exception in thread "main" java.lang.AssertionError: Message to display(String)
was null
        at Assert2.display(Assert2.java:8)
        at Assert2.main(Assert2.java:4)

C:\>java -enableassertions Assert2
This is a test of the assertion mechanism
Exception in thread "main" java.lang.AssertionError: Message to display(String)
was null
        at Assert2.display(Assert2.java:8)
        at Assert2.main(Assert2.java:4)

*/