Main Page

Previous Next

Assertions

Every so often you will find that the logic in your code leads to some logical condition that should always be true. If you test an integer and establish that it is odd, it is certainly true that it cannot be even for instance. You may also find yourself writing a statement or statements that, although they could be executed in theory, in practice they never really should be. I don't mean by this the usual sorts of errors that occur such as some incorrect data has been read in somehow. This should be handled ordinarily by the normal code. I mean circumstances where if the statements were to be executed, it would imply that something was very seriously wrong with the program or its environment. These are precisely the circumstances to which assertions apply.

A simple assertion is a statement of the form:

assert logical_expression;

Here, assert is a keyword and logical_expression is any expression that results in a value of true or false. When this statement executes, if logical_expression evaluates to true, then the program continues normally. If logical_expression evaluates to false, the program will be terminated with an error message starting with:

java.lang.AssertionError

This will be followed by more information about where the error occurred in the code. When this occurs, the program is said to assert.

Let's consider an example. Suppose we have a variable of type int that stores the number of days in the current month. We might use it like this:

if(daysInMonth == 30) {
  System.out.println("Month is April, June, September, or November");

} else if(daysInMonth == 31) {
  System.out.println(
             "Month is January, March, May, July, August, October, or December.");
} else {
  assert daysInMonth == 28 || daysInMonth == 29;
  System.out.println("Month is February.");
}

We are presuming that daysInMonth is valid – that is, it has one of the values 28, 29, 30 or 31. Maybe it came from a file that is supposed to be accurate so we should not need to check it, but if it turns out not to be valid, the assertion will check it.

We could have written this slightly differently:

if(daysInMonth == 30) {
  System.out.println("Month is April, June, September, or November");

} else if(daysInMonth == 31) {
  System.out.println(
             "Month is January, March, May, July, August, October, or December.");

} else if(daysInMonth == 28 || daysInMonth == 29) {
  System.out.println("Month is February.");

} else {
  assert false;
}

Here, if daysInMonth is valid, the program should never execute the last else clause. An assertion with the logical expression as false will always assert, and terminate the program.

If you include assertions in your code you must compile the code with the command line option -source 1.4 specified. This is necessary for backwards compatibility reasons. It is possible that Java programs that predate the assertion facility may have used the word assert as a name somewhere. Without the -source 1.4 option specified for the compiler, such programs can execute normally. For assertions to have an effect when you run your program, you must specify the -enableassertions option, or its abbreviated form -ea. If you don't specify this option, assertions will be ignored.

There is a slightly more complex form of assertions that have this form:

assert logical_expression : string_expression;

Here, logical_expression must evaluate to a boolean value, either True or False. If logical_expression is False then the program will terminate with an error message including the string that results from string_expression.

For example, we could have written the assertion in the last code fragment as:

assert false : "daysInMonth has the value" + daysInMonth;

Now if the program asserts, the output will include information about the value of daysInMonth.

Let's see how it works in practice.

Try It Out – A Working Assertion

Here's some code that is guaranteed to assert – if you compile and execute it right:

public class TryAssertions {
  public static void main(String args[]) {
    int daysInMonth = 32;
    if(daysInMonth == 30) {
      System.out.println("Month is April, June, September, or November");

    } else if(daysInMonth == 31) {
      System.out.println(
             "Month is January, March, May, July, August, October, or December.");

    } else if(daysInMonth == 28 || daysInMonth == 29) {
      System.out.println("Month is February.");

    } else {
      assert false;
    }
  }
}

Don't forget, you must compile this with the -source 1.4 option specified:

javac -source 1.4 TryAssertions.java

You must also execute it with the command:

java -enableassertions TryAssertions

You should then get the output:

java.lang.AssertionError
    at TryAssertions.main(TryAssertions.java:1)
Exception in thread "main"

How It Works

Since we have set daysInMonth to an invalid value, the assertion statement is executed, and that results in the error message. You could try the other form of the assertion:

assert false : "daysInMonth has the value " + daysInMonth;

Now you should see that the output includes the string resulting from the second expression in the assertion statement:

java.lang.AssertionError: daysInMonth has the value 32
    at TryAssertions.main(TryAssertions.java:1)
Exception in thread "main"

We will use assertions from time to time in the examples in subsequent chapters.

Previous Next
JavaScript Editor Java Tutorials Free JavaScript Editor