Chapter 13: I/O, Applets, and Other Topics 307
Here is an example that usesassert. It verifies that the return value ofgetnum( )is positive.
// Demonstrate assert.
class AssertDemo {
static int val = 3;
// Return an integer.
static int getnum() {
return val--;
}
public static void main(String args[])
{
int n;
for(int i=0; i < 10; i++) {
n = getnum();
assert n > 0; // will fail when n is 0
System.out.println("n is " + n);
}
}
}
To enable assertion checking at run time, you must specify the-eaoption. For example,
to enable assertions forAssertDemo, execute it using this line:
java -ea AssertDemo
After compiling and running as just described, the program creates the following output:
n is 3
n is 2
n is 1
Exception in thread "main" java.lang.AssertionError
at AssertDemo.main(AssertDemo.java:17)
Inmain( ), repeated calls are made to the methodgetnum( ), which returns an integer value.
The return value ofgetnum( )is assigned tonand then tested using thisassertstatement:
assert n > 0; // will fail when n is 0
This statement will fail whennequals 0, which it will after the fourth call. When this happens,
an exception is thrown.