Yesterday in the view of the NIO source code, see such a sentence, immediately confused forced:
ASSERT (i >= 0);
Assert keyword I have an image, Chinese is called assertion. But has never been to understand its function, today in the cold to take time, put my summary of the code out:
1. The JVM turns off assert by default and can be opened by the-ea command
(1) The Java command turns on assert
Java-ea $classname
(2) Enable Assert in eclipse
On the project right-click Run as---run configurations-Arguments Tab in the VM Arguments fill in-ea and apply
or Windows-Preferences, Java-installed JREs Select JDK Click Edit, enter-ea in default VM arguments: and finish
2. How assert is used
- Assert expression;
- Assert Expression1:expression2;
Expression2 is the errormsg of Java.lang.AssertionError.
assert(1>2): (1>2? ") Correct ":" This is the ErrorMsg ");
SYSTEM.OUT.PRINTLN ("Success");
Exception in thread "main" Java.lang.AssertionError:This is the errormsg
(Oh shit, the egg hurts the editor, it doesn't work)
3. Assert the applicable scenario
- Where the program is not expected to arrive under normal circumstances: assert false;
- Parameter values that can be used to check private methods
- Preconditions and post conditions for the test method
- Used to check the invariant state of a class to determine that in any case, a variable state must meet
4. Assert does not apply to the scene
- Do not use assert as a parameter check for the public method, the parameters of the public method are always executed
- Assert statements must not have any boundary effects, do not use ASSERT statements to modify variables and change the return value of a method.
Summarize:
Assert is often used to check for some key that has a significant impact on the program.
Java about assert