Java Reference
In-Depth Information
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 logic-
al_expression is false then the program terminates with an error message including the string that results
from string_expression .
For example, you 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 includes 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 correctly:
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;
}
}
}
TryAssertions.java
Don't forget that, after you have compiled the program, you must execute it with assertions enabled, like
this:
java -enableassertions TryAssertions
Search WWH ::




Custom Search