Java Reference
In-Depth Information
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 contin-
ues normally. If
logical_expression
evaluates to
false
, the program is terminated with an error message
starting with:
java.lang.AssertionError
This is 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 you have a variable of type
int
that stores the number of days in the
current month. You 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.");
}
You 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 you should not need to check it, but if it turns out not
to be valid, the assertion detects it and ends the program.
You 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
always asserts and terminates the program.
More Complex Assertions