Java Reference
In-Depth Information
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 .
Search WWH ::




Custom Search