Java Reference
In-Depth Information
Making the assert statement work . The assert statement may not work in your system. Some
IDEs have a switch that tells whether the assert statement should be allowed.
For example, if your version of DrJava does not allow the assert statement,
select menu edit item preferences . In the window that opens, click category
Miscellaneous in the lefthand column and then check the box Allow assert key-
word in Java 1.4 .
If you are using a command-line window to compile a Java program, then
you need the -source 1.4 option to enable assertions, as shown below. This is
needed for backward compatibility reasons.
javac -source 1.4
assertions . Examples are preconditions of methods, postconditions of methods,
class invariants, and loop invariants. Java 1.4 has a new statement, the assert
statement , which comes in one of two forms:
assert boolean-expression ;
assert boolean-expression : expression ;
This statement is executed as follows. The boolean-expression is evaluated;
if it is true , execution of the statement is finished. If it is false , an Assertion-
Error is thrown, which (for the first form above) prints the following message
and terminates the program:
at Funcs.testPrint(
For the second form, the value of the expression is printed as well —it is the
detail message of the thrown AssertionError . For example, if this value is
"hey, it is 5" , then this is printed:
java.lang.AssertionError: hey, it is 5
at Funcs.testPrint(
The assert statement, inserted at judiciously chosen places, can alert you to
misguided beliefs and therefore help you debug your program. For example, sup-
pose you previously wrote the following code:
/** Put into double field 1 the fahrenheit value for centigrade value in double field 0 */
public Object buttonPressed() {
double b= getDoubleField(0);
setStringField(0, "Centigrade");
setDoubleField(1, TempConvert.FahrFromCent(b));
setStringField(1, "Fahrenheit");
return null ;
Figure 14.5:
Method buttonPressed used to test function FahrFromCent
Search WWH ::

Custom Search