Assertions in the Java programming language
Are you ready for Java assertions? This fun feature of Java is used to define the boolean condition in a program. In this article, Adrian D. Finlay explores how developers can make the most of this condition and how they can avoid AssertionErrors.
Assertions are a development tool and programming language feature used to check if a conditional expression evaluates to true when the program is run. They are useful in the testing and development process and are typically omitted for production code. A key reason for this is that they require command line flags to be enabled, thus limiting proper functioning portability if said command line flags are enabled. As such, they are not recommended for production code; they were not designed for this. They can replace situations where programmers used to check for with if statements. They are much more compact then if statements and if assertions are not enabled at run-time, they are ignored. Assertions are accomplished in Java with the assert keyword. An AssertionError is thrown if the condition evaluates to false. We have Joshua Bloch to thank for this language feature.
To configure assertion options one must use either the -ea or -da command line flags to enable or disable assertions with the command line tool: “java”. For example, “java -ea Assert” where Assert is a java class file. You may also specify a specific class or package as follows. For a class: “-ea:Class”, “-ea:Package/Class”. For a package (and it’s sub-packages): “-ea:Package…”. Notice the ellipses (three succeeding periods), they are part of the format.
Within java code assertions take the following two forms:
- assert condition;
- assert condition: expression;
In the first form, condition is a conditional expression in java that results to True or False. In the second form, an expression is executed if the condition is false. This may be any expression that is not of type void. The String representation of the result of this Expression will be used in forming the AssertionError object. In both cases, an AssertionError is thrown if the conditional expression results to false.
Basic Assertion usage:
Basic Assertion usage with example of Expression added:
Basic Assertion usage with Custom Class instance used as expression:
Catching the AssertionError exception object generated by assert:
Capturing the AssertionError object for use outside of try-catch:
Note! For the purpose of completeness, we have shown how to catch an AssertionError. However, you should never attempt to catch Errors, only Exceptions, if needed!
Program that parses command line arguments and checks against a condition. Remember: this is advised against for production code.
And much more. Play around with it and let me know how you like it :)
Want the source? Grab it here.