Contact Us or call 1-877-932-8228


Java 1.4 added the concept of assertions, code lines that test that a presumed state actually exists

  • If the state is not as presumed, then an AssertionError will be thrown.
  • Assertions are not intended for testing values that could be expected; they are intended to be used when it is believed that a state exists, but we are not absolutely sure we have covered all the possible avenues that affect the state.

To use an assertion in code:

assert (condition) [: messageExpression];

The optional messageExpression will be converted to a String and passed as the message to the AssertionError constructor, so it cannot be a call to a function declared as void.

For example, perhaps we are using a third-party function that is specified to return a double value between 0 and 1, but we'd like to guarantee that is the case.

Code Sample:

public class AssertionTest {

  public static void main(String[] args) {
    double value = thirdPartyFunction();
    assert (value >= 0 && value < 1) : 
       " thirdPartyFunction value " + value + " out of range";
    System.out.println("Value is " + value);

  public static double thirdPartyFunction() {
    return 5.0;

If the function returns a value outside of our expected range, like 5.0, the assertion condition will evaluate to false, so an AssertionError will be thrown with the message "thirdPartyFunction value 5.0 out of range."

Note: in a 1.4 compiler, you must inform the compiler that you are compiling your code under Java 1.4 rules to use assertions, using the -source 1.4 command line switch:

javac -source 1.4

In Java 5 and later this is not necessary.

Assertions are used for debugging a program, and usually not enabled for production runs. You must specifically enable assertions when you run the program, by using the command line switch -enableassertions (or -ea).

java -enableassertions ClassName
java -ea ClassName

Oracle's "rules" for assertions emphasize that they will be disabled most of the time:

  • They should not be used for checking the values passed into public methods, since that check will disappear if assertions are not enabled.
  • The assertion code shouldn't have any side effects required for normal operation.