Assertions

The assert keyword enables Java programmers to make use of 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 a 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 a 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."

By the way

FUBAR is an acronym popular among computer programmers that means "fouled up beyond all recognition" or "fouled up beyond all repair." A saltier version that uses a different F word is even more popular.


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.disconnected();


If the expression that follows 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 JDK 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 turned off by default in the JDK (and presumably other tools as well). JDK users must use command-line arguments to turn on assertion support. To compile a class that contains assert statements, use the -source 1.5 option, as in the following example:

javac -source 1.5 Nuke.java


The -source 1.5 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 also must enable assertions when running a Java class with the JDK 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


Watch Out!

Because anyone can run a Java program with assertions turned off, you shouldn't depend too heavily on them. They're most useful when you run your own code and are testing its reliability.


      
Comments