Sams Teach Yourself Java 2 in 24 Hours

Sams Teach Yourself Java 2 in 24 Hours

By Rogers Cadenhead

Assertions

Sun Microsystems did something in Java 2 version 1.4 that hasn't happened often in the history of the language: It added a new keyword, assert.

The assert keyword enables Java programmers to use assertions, a technique that's supposed to improve the reliability of software. An assertion is a Boolean true-or-false expression that represents something that should be true at that spot in the program. Here's an example:

assert speed > 55; 

This statement asserts that the speed variable has a value greater than 55. It's another way for a programmer to say, "I expect speed to be greater than 55 at this position, and if it isn't, my program would be completely FUBAR."

Assertions are a way to ensure that a program is running as expected.

The assert keyword must be followed by something that produces a Boolean value: an expression, a boolean, or a method that returns a boolean. Three examples:

assert pointX = 0; 

assert endOfFileReached; 

assert network.noLongerConnected(); 

If the expression used with the assert keyword is false, an AssertionError exception will be thrown. You can make these errors more meaningful by specifying an error message in an assert statement. Add a colon and text at the end, as in this example:

assert temperature > 2200 : "Core breach in Sector 12!"; 

If you're using the SDK interpreter, here's how it responds to an AssertionError exception:

Exception in thread "main" java.lang.AssertionError: Core breach in Sector 12! 
    at Nuke.power(Nuke.java:1924) 

Assertions are offered in Java 1.4, but are turned off by default in the SDK (and presumably other tools as well).

SDK users must use command-line arguments to turn on assertion support. To compile a class that contains assert statements, use the -source 1.4 option, as in the following example:

javac -source 1.4 Nuke.java 

The -source 1.4 option causes the compiler to support assertions in the class file (or files) that it produces. An error will result if you try to compile a program that contains assert statements but do not use this option.

You must also enable assertions when running a Java class with the SDK interpreter. The easiest way to do this is to use the -ea argument, which enables assertions for all classes (except those that are part of the Java class library):

java -ea Nuke 

To enable assertions only in one class, follow -ea with a colon and the name of the class, as in this example:

java -ea:Nuke Nuke 

To enable assertions only in one package, follow -ea with a colon and the name of the package:

java -ea:com.prefect.power Nuke 

Share ThisShare This

Informit Network