Assertion: The so-called assertion, is a new feature added after jdk1.4. It is used primarily during code development and testing, to judge certain critical data, and if the key data is not the data your program expects, the program warns or exits. When the software is officially released, you can cancel the assertion section of the code. Using assert as a keyword in Java, it can be seen that Java is very important to assertions, because if it is not very significant, the development of a class directly, there is no need to define a new keyword. Grammar 1:assert expression; Expression represents a Boolean type that, if true, continues to run normally, and if False, the program exits Grammar 2:assert Expression1:expression2; Expression1 is a Boolean expression, Expression2 is a basic type or an object type, and if expression1 is true, the program ignores expression2 to continue running, and if expression1 is false, Run expression2, and then quit the program. application Example 1: [Java]View Plaincopy
- public class Assertiondemo {
- The value of this member variable can change, but must eventually return to the original value 5
- static int i = 5;
- public static void Main (string[] args) {
- Assert i==6;
- System.out.println ("If the assertion is normal, I will be printed");
- }
- }
Operation Result: Example two: [Java]View Plaincopy
- public class Assertiondemo {
- public static void Main (string[] args) {
- int i = 3;
- switch (i) {
- Case 1:
- System.out.println ("normal");
- Break
- Case 2:
- System.out.println ("normal");
- Break
- Case 5:
- System.out.println ("normal");
- Break
- Default
- Assert false: The value of "I is invalid"; If the value of I is not what you want, the program warns you to exit
- }
- System.out.println ("If the assertion is normal, I will be printed");
- }
- }
Note that in Eclipse, the assertion feature is turned off by default, and if we need to use this feature, we need to open it manually.To open a step:
In VM arguments input-ea is on (enableassertion) input-da is off (disenableassertion) Note: The assertion function is used for software development and testing, that is, to delete the assertion of the part of the statement, the structure and operation of your program should not have any changes, do not use the assertion as a function of the program used |