Assertion is a Java statement, Boolean expression,ProgramThe member thinks that the expression value should be true during program execution. The system calculates this Boolean expression to execute assertions. If this expression is false, the system reports an error.
Assertions are declared using the assert keyword. There are two formats for using the assert function:
Assert expression; or assert expression: detailmessage;
Expression is a Boolean expression, and detailmessage is a value of the basic data type or object type. When an asserted statement is executed, Java calculates the expression value. If its value is false, an assertionerror error is thrown.. For the second type of asserted statement with a detailed information, the assertionerror class will be used to construct a method that matches the Data Type of the message. Because the assertionerror class is a subclass of the error class, when the asserted value is false, the program will display a message on the console and terminate the program execution.
By default, the asserted function is not enabled in eclipse, so you will not see the effect when using the asserted function. First, use the following steps to enable the asserted function:
In myeclipse
Windows --> preferences ---> JAVA ---> installed jres ---> click the JDK in use ---> edit --->
Enter-ea in the default VM arguments text box
For example
After opening, use the followingCodeTest:
Public Class Aseerttest { Public Boolean Flag = True ; // Change the flag value and view the console output Public Boolean Isvalid (){ Return Flag ;} Public Static Void Main (string ARGs []) {aseerttest assertion = New Aseerttest (); Assert Assertion. isvalid (): "flag must be true! " ; System. Out. println ( "Assert end" );}}
If you change the flag value to false to make the condition unable to pass the test, the following exception will be thrown, indicating that the asserted has taken effect.