One. Overview
Assert: Represents an assertion
Two. Grammar
In Java, the Assert keyword was introduced from Java SE 1.4, in order to avoid using the Assert keyword in the old version of Java code to cause an error, Java does not start the assertion check by default (at this point, all assertion statements will be ignored!). ), if you want to turn on assertion checking, you need to turn on the switch-enableassertions or-ea.
The Assert keyword syntax is simple and there are two ways to use it:1. Assert <boolean expression >If the <boolean expression > is True, the program continues execution. If False, the program throws a assertionerror and terminates execution.2. Assert <boolean expression >: < error message expression >If the <boolean expression > is True, the program continues execution. If False, the program throws a Java.lang.AssertionError and input < error message expression >. Three. An example is given below to illustrate its usage by example:
1 Public classAssertfoo {2 Public Static voidMain (String args[]) {3 //Assertion 1 result is true, continue execution down4 assert true;5System.out.println ("Assertion 1 no problem, go! ");6System.out.println ("\ n-----------------\ n");7 //Assertion 2 result is false, program terminates8 assert false: "The assertion failed, and the information for this expression will be output when the exception is thrown!" ";9System.out.println ("Assertion 2 no problem, go! ");Ten } One}
Create a class under Eclipse to save the compilation run, the output is visible and does not perform an assert, then how to set the open assertion under Eclipse, see the following method: Configure the Run Configurations menu bar--->run--->run Configurations Open the Configuration interface, enter the-ea in the VM argument, as shown in the test class run configuration I added-ea, and then in the test's main function call Class A, in Class A asserted, assert execution I in Class A run configuration added-ea , and then calls the Class A in the main function of test, adds an assertion in Class A, asserts that the assertion does not execute the result: Pay attention to the green box and look at the code above;-) four. Recommended personal advice to avoid using assert assertions, the use of really inconvenient, not as easy as juint or debug with breakpoints, but also to see the values of the preceding variables, analysis of the reasons
Java Foundation outrageous one: Assert keyword