Assertion notes assertions are used to stop a program and display an error message assertions should be used to catch logic problems in programs that are unexpected assertions should not be used for normal data validation, especially not user input the assertion mechanism has a lot of overhead so assertions are not normally enabled programs get compiled with assertions, but need to have the -enableassertions or -ea option to the java program to work one syntax form is: assert condition; // error displayed if condition false another syntax form is: assert condition:expression; // error and expression displayed if condition false you can enable system assertions (not demonstrated here) you can enable assertions for some classes and disable them for others (not demonstrated here)
Example of 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) */
Example os 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) */