1. Assert (Assert[? ' S?t]Vt.maintain, hold, assert, stand, claim)
Function: Actually is used to debug the program, but the visual use of very little.
Let's take a look at two examples and then explain:
1.1. First define a Testassert class
1 Public classtestassert{2 Public Static voidMain (string[] args) {3Testassert TA =NewTestassert ();4Ta. Test (-99);5 }6 7 Public voidTest (intAge ) {8 //assert keyword, plus a Boolean expression, but when the expression evaluates to False, the program exits9 //and throws a assertionerror, so the assertion is the error levelTen assertage>=0;//continue running if conditions are met OneSystem.out.println ("Continue, enter the age is:" +Age ); A } -}
View Code
First compile javac Testassert.java
Then normal execution: java testassert, the result is:
Start the assertion, Java-ea Testassert , and the result is:
or using java-enableassertions Testassert, the result is the same:
As you can see, the thrown type is java.lang.AssertionError
As for the command to explicitly close the assertion is not tested, the personal feeling that is to take off the pants fart thing, interested can test their own.
1.2. An example of an assertion followed by a message:
or use the class Testassert above to modify it slightly:
1 Public classtestassert{2 Public Static voidMain (string[] args) {3Testassert TA =NewTestassert ();4Ta. Test (-99);5 }6 7 Public voidTest (intAge ) {8 //assert keyword, plus a Boolean expression, but when the expression evaluates to False, the program exits9 //and throws a assertionerror, so the assertion is the error levelTen assertAge>=0: "Can not enter this unreasonable age ah";//continue running if conditions are met OneSystem.out.println ("Continue, enter the age is:" +Age ); A } -}
View Code
First compile javac Testassert.java
Then normal execution: java testassert, the result is:
Because the default does not open the assertion, so the result is the same as above,
Start the assertion, Java-ea Testassert , and the result is:
Obviously, the result is output of the string we just wrote, which can enhance readability.
or using java-enableassertions Testassert, the result is the same:
2. Use the method, (command line required) 2.1. Turn on assertion function (The default is off)
java -ea testassert----(EA is the abbreviation for enable and assertions )
Or:java -enableassertions testassert
2.2. Off (although the default is off, but you can also display to close it, in fact, this parameter does not, haha)
java -da Testassert
Or:java -disableassertions Testassert
3. Usage format for assertions:
3.1. General format assert Boolean expression ;
eg: int a = 0;
Assert a>100;
3.2. Enhanced format assert Boolean expression: "string";
Assertion of Java (assert)