As explained, you can specify the message displayed when an assertion fails. For example,
if you substitute
assert n > 0 : "n is negative!";
for the assertion in the preceding program, then the following output will be generated:
n is 3
n is 2
n is 1
Exception in thread "main" java.lang.AssertionError: n is
negative!
at AssertDemo.main(AssertDemo.java:17)
One important point to understand about assertions is that you must not rely on them
to perform any action actually required by the program. The reason is that normally, released
code will be run with assertions disabled. For example, consider this variation of the preceding
program:
// A poor way to use assert!!!
class AssertDemo {
// get a random number generator
static int val = 3;
// Return an integer.
static int getnum() {
return val--;
}
public static void main(String args[])
{
int n = 0;
for(int i=0; i < 10; i++) {
assert (n = getnum()) > 0; // This is not a good idea!
System.out.println("n is " + n);
}
}
}
In this version of the program, the call to getnum( ) is moved inside the assert statement.
Although this works fine if assertions are enabled, it will cause a malfunction when assertions
are disabled, because the call to getnum( ) will never be executed! In fact, n must now be
initialized, because the compiler will recognize that it might not be assigned a value by the
assert statement.
Assertions are a good addition to Java because they streamline the type of error checking
that is common during development. For example, prior to assert, if you wanted to verify that
n was positive in the preceding program, you had to use a sequence of code similar to this:
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home