Assertion concept

Assertions used to prove and test the hypothesis of the program,For example "here the value is greater than 5".

Assertions can be completely removed from the code at runtime,So it has no effect on the speed of the code.

Use of assertions

There are two ways to assert:

One is assert<<boolean expression>

The other is assert<<Boolean expression> ;:<<Detailed description> ;.

If the value of the boolean expression is false, an assertionerror exception will be thrown;the detailed description is that the description text of the assertionerror exception is compiled using the javac –source 1.4 myclass.java example:

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");

With the introduction of a new keyword,So you need to add extra parameters when compiling,To compile successfully,You must use jdk1.4's javac with 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 runs using the assertion function also requires additional parameters (and requires a number of command line parameters), such as:

 java -ea assertexample 1

The output of the program is:

testing assertion that x == 10
exception in thread "main" java.lang.assertionerror:our assertion failed
at assertexample.main (assertexample.java:20)

Because the input parameter is not equal to 10, the assertion function causes the program to throw an assertion error,Attention is wrong, This means that the program has a serious error and will force exit.Assertions use a boolean value, if its value is not true then an assertionerror is thrown and the program is terminated.

Assertion Recommended Use

Used to verify the internal logic in the method,include:

Intrinsic invariant Control flow invariant Post-conditions and class invariants

Note:It is not recommended to check preconditions in public methods.

Masking assertions at runtime

Assert assertions at runtime,You can use the following methods:

java --disableassertions or java --da class name

Allow assertions at runtime,You can use the following methods:

java --enableassertions or java -ea class name

  • Previous A detailed introduction to PHP comparison operators
  • Next The web page passes the value from the pop-up page radio box to the parent page