An assertion is an affirmation that the return value of a result is correct. If the return value of the result is incorrect, an assertion check will prompt an error message

Assertion format:

assert booleanThe expression;assert booleanExpression: DetailsCopy the code

If the Boolean expression above results in true, no error message is displayed;

If false, an error message is displayed. If no detailed information is specified, the system uses the default error message.

public class Test{
    public static void main(String[] args) {
        int x[] = {1.2.3};// Define an array of 3 lengths
        assert x.length ==0;// It must be wrong to assert that the array length is 0}}Copy the code

In this program, the length of the array x cannot be zero, so the result is incorrect. Running the program does not get any results. Java designed this keyword with system functions in mind. So assertions do not work when the program is running properly. To make assertions work, you need to add the following parameters to the Java runtime:

-enableassertions are also short for -EA. Compile program: javac Test. Java Validation program: java-EA TestCopy the code

If you want to display your own error message, you can use another assertion declaration format:

public class Test{
    public static void main(String[] args) {
        int x[] = {1.2.3};// Define an array of 3 lengths
        assert x.length ==0:"Array length not zero";// It must be wrong to assert that the array length is 0}}Copy the code

Note:

  • Although an assertion returns a Boolean value, it is not considered a conditional statement
  • Assertions, while they have the ability to check the results of a run, are generally discouraged in development