Basic usage of assert

An assertion is a statement in a program that checks a boolean expression. A correct program must ensure that the value of the boolean expression is true; if the value is false, it means that the program is already in an incorrect state, and the system will Give a warning and exit. Generally speaking, assertion is used to ensure the most basic and critical correctness of the program. Assertion checks are usually turned on during development and testing. To improve performance, assertion checking is usually turned off after the software is released. The following is a brief introduction to the implementation of assertion in Java.

Syntactically, in order to support assertion, Java adds a keyword assert. It includes two kinds of expressions, as follows:

1. assert expression1;
2. assert expression1: expression2;

expression1 represents a boolean expression, and expression2 represents a primitive type, expression, or an Object, which is used to output an error message when it fails.

At runtime, if assertion is turned off, these statements will have no effect. If the assertion feature is turned on, then the value of expression1 will be evaluated, and if its value is false, the statement will throw an AssertionError object.

The sample code is as follows:

package com.chzhao.test;

public class AssertDemo { public static void main(String[] args) { test1(-5); test2(-3); } private static void test1(int a){ assert a > 0; System.out.println(a); } private static void test2(int a){ assert a > 0 : "something goes wrong here, a cannot be less than 0"; System.out.println(a); } }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324982722&siteId=291194637