Java basics 1: assert keyword, assert
I. Overview
Assert: Indicates assertion.
II. Syntax
In Java, the assert keyword is introduced from java se 1.4. to avoid errors caused by the use of the assert keyword in Java code of earlier versions, by default, Java does not start assertion checks during execution (at this time, all assertion statements will be ignored !), If you want to enable the assertions check, you must enableassertions or-ea.
The syntax of the assert keyword is very simple. There are two usage methods: 1. assert <boolean expression> If <boolean expression> is true, the program continues to execute. If it is false, the program throws an AssertionError and terminates the execution. 2. assert <boolean expression>: <error message expression> If <boolean expression> is true, the program continues to execute. If it is false, the program throws a java. lang. AssertionError and enters the <error message expression>. 3. The example below provides an example to illustrate its usage:
1 public class AssertFoo {2 public static void main (String args []) {3 // if the result of asserted 1 is true, execute 4 assert true; 5 System. out. println ("assertion 1 is okay, Go! "); 6 System. out. println ("\ n --------------- \ n"); 7 // assert 2 results in false, program termination 8 assert false: "assert failed, the information of this expression will be output when an exception is thrown! "; 9 System. out. println (" assertion 2 is okay, Go! "); 10} 11}
Create a class in Eclipse to save the compilation and run, and the output result is visible and does not execute assert. So how can I set enable assertions in Eclipse? See the following method: configure Run Configurations menu bar ---> Run Configurations open the configuration page and enter-ea in the VM argument, as shown in-ea, then, in the main function of Test, Class A is called, and an assertion is added to Class A. For assertion execution, I added-ea in the Class A running configuration, then, in the main function of Test, Class A is called, and an asserted is added to Class A. The asserted execution result is not executed. Note the following, if you don't pay attention to it, check the above Code.-) during the test, the output sequence of sysout and exception throw is erratic. For details, please refer to the notes. Thank you very much for your answers.