Java examples for Language Basics:assert
A Simple Test Class to Test the Assert Statement
public class Main { public static void main(String[] args) { int x = 10 + 15; assert x == 100:"x = " + x; // should throw an AssertionError }/*from w w w.j a v a2 s .c o m*/ }
Try to run the Main class using the following command:
java -ea Main
Command-Line Switches to Enable/Disable Assertions at Runtime
Command-Line Switch | Description |
---|---|
-enableassertions or -ea | Used to enable assertions at runtime for system classes as well as user-defined classes. You can pass an argument to this switch to control the level at which assertions are enabled. |
-disableassertions or -da | Used to disable assertions at runtime for system classes as well as user-defined classes. You can pass an argument to this switch to control the level at which assertions are disabled. |
-enablesystemassertions or -esa | Used to enable assertions in all system classes. You cannot pass any arguments to this switch. |
-disablesystemassertions or -dsa | Used to disable assertions in all system classes. You cannot pass any arguments to this switch. |
/* Enable assertions in all system classes */ java -esa Main /* Enable assertions in all user-defined classes */ java -ea Main /* Enable assertions in com.mypkg package and its sub-packages */ java -ea:com.mypkg... com.mypkg.assertion.AssertTest /* Enable assertions in the unnamed package in the current directory */ java -ea:... com.mypkg.assertion.AssertTest /* Enable assertions in com.mypkg.assertion.AssertTest class */ java -ea:com.mypkg.assertion.AssertTest com.mypkg.assertion.AssertTest /* Enable assertions in p1 package and all its sub-packages and disable assertion for p1.p2.MyClass */ java -ea:p1... -da:p1.p2.MyClass com.mypkg.assertion.AssertTest