eteran object-oriented language programmers who have used non-Java languages are accustomed to having assertions in their development toolbox. An assertion is an expression that evaluates to either true
. Assertion failures are treated as unchecked exceptions. Programmers use such failures as an indication that the program deviated from the intended functionality. Assertions can help improve the quality of your code by letting you find and fix problems before you ship it to production.
In the past, Java had no assertions feature to help programmers test assumptions about the state of their applications during execution. Fortunately, Sun included assertions as part of the Java 2 Standard Edition (J2SE) 1.4 as a result of Java Specification Request (JSR) 41
proof that the JSR process can work. This article introduces you to the assertions feature. You'll see when and when not to use assertions in your code.
Designing By Contract
The "Design By Contract" theory states that an application creator and application consumer have a contract that determines how the application should function. Assertions follow the theme of designing by contract, because you can use them to verify that contractual line items have been met. Assertions test the correctness of assumptions made in your program.
Exceptions versus Assertions
You might wonder why assertions are even needed when exceptions are available. You use Java exceptions to handle unusual conditions during execution. On the other hand, you use assertions to affirm or assert conditions which you assume are true. In other words, assertions test to see if a condition occurs that should never happen. Assertions are meant to be development aids. As it's highly likely that assertions won't be enabled during production runs (they're off by default), your program should not rely on assertions to execute correctly at runtime.
For example, you might use an assertion in your code to show that the execution path never reaches the default condition in a switch statement (if that is what you intended). Also, you might assert that only one argument is passed in as a command line argument (again, if that is what you intended).