Home  >  Article  >  Java  >  What are Java assertions

What are Java assertions

WBOY
WBOYforward
2023-05-05 10:28:131869browse

Explanation

1. Assertion is the content introduced after jdk1.4 and is represented by the keyword assert.

2. To check whether the parameters are legal in the program, the if statement is generally used. However, the code still exists in the program after the test is completed. At this time, the assert assertion needs to be introduced. The assertion is not part of the program and will be deleted after the test is completed. This code (Note: idea asserts off by default and needs to be started by adding the -ea running parameter)

Grammar format

assert condition : expression(可省略)

If the condition is not established, the program will execute expression and then terminate Execute and throw AssertionError. If the condition is true, the program will run normally.

Example

public static void main(String[] args){
    int sum = 6;
    assert sum==5 : "sum不等于5";
    System.out.println("---如果断言正常---");
 
}

The above is the detailed content of What are Java assertions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete