Here is an example that uses assert. It verifies that the return value of getnum( ) 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 -ea option. For example,
to enable assertions for AssertDemo, 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)
In main( ), repeated calls are made to the method getnum( ), which returns an integer value.
The return value of getnum( ) is assigned to n and then tested using this assert statement:
assert n > 0; // will fail when n is 0
This statement will fail when n equals 0, which it will after the fourth call. When this happens,
an exception is thrown.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home