assert expression1;
or (full version):assertexpression1 : expression2;
Where:java –enableassertions CarManager
or this for short:java –ea CarManager
Assertion can be enabled or disable specifically for named classes or packages. For more information on how to enable and disable assertion, read this article.public class AssertionExample {
public static void main(String[] args) {
// get a number in the first argument
int number = Integer.parseInt(args[0]);
assert number <= 10; // stops if number > 10
System.out.println("Pass");
}
} When running the program above with this command:java -ea AssertionExample 15
A java.lang.AssertionError error will be thrown: Exception in thread "main" java.lang.AssertionError at AssertionExample.main(AssertionExample.java:6) But the program will continue and print out “Pass” if we pass a number less than 10, in this command:java -ea AssertionExample 8
And the following example is using the full version of assert statement:public class AssertionExample2 {
public static void main(String[] args) {
int argCount = args.length;
assert argCount == 5 : "The number of arguments must be 5";
System.out.println("OK");
}
} When running the program above with this command: java -ea AssertionExample2 1 2 3 4
it will throw this error: Exception in thread "main" java.lang.AssertionError: The number of arguments must be 5 at AssertionExample2.main(AssertionExample2.java:6) Generally, assertion is enabled during development time to defect and fix bugs, and is disabled at deployment or production to increase performance. See all keywords in Java.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.