The concept of assertion
Assertions are used to prove and test the assumptions of programs, such as "the value here is greater than 5".
Assertions can be completely removed from the code at runtime, so they have no effect on the running speed of the code.
Use of assertions
There are two ways to assert:
One is assert<<Bolean expression>>;
The other is assert<<Bolean expression>>:<<Detail description>>.
If the value of the boolean expression is false, an AssertionError exception will be thrown; the description text of the AssertionError exception is compiled using javac source 1.4 MyClass.java is as follows:
public class AssertExample { public static void main(String[] args) { int x = 10; if (args.length > 0) { try { x = Integer.parseInt(args[0]); } catch (NumberFormatException nfe) { /* Ignore */ } } System.out.println("Testing assertion that x == 10"); assert x == 10 : "Our assertion failed"; System.out.println("Test passed"); }} : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : :
Since a new keyword is introduced, additional parameters need to be added during compilation. To successfully compile, you must use JDK1.4 javac and add the parameter '-source 1.4'. For example, you can use the following command to compile the above Code:
javac -source 1.4 AssertExample.java
The above program needs to use additional parameters (and a numeric command line parameter is required) when running the assertion function, for example:
java -ea AssertExample 1
The output of the program is:
Testing assertion that x == 10Exception in thread "main" java.lang.AssertionError:Our assertion failedat AssertExample.main(AssertExample.java:20)
Since the input parameter is not equal to 10, the assertion function causes the program to throw an assertion error when running. Note that it is an error, which means that a serious error occurred in the program and will be forced to exit. Asserts that the boolean value is used, if its value is not true, an AssertionError is thrown and the program is terminated.
Assert recommended usage
Used to verify internal logic in methods, including:
Note: It is not recommended for checking preconditions within public methods.
Runtime blocking assertions
To block assertions during runtime, you can use the following method:
To allow assertions when running java disableassertions or java da class name, you can use the following method:
java enableassertions or java ea class name