JAVATM MASTER

assert Keyword Explained

Back to Table of Contents

JavaTM version 1.4 (called Merlin) has added a new keyword, a very rare occurance, and this new keyword, assert, is used for debugging purposes. The compiler will throw an error if you use assert as a variable name or a class name in 1.4.

When assertions are enabled, as in the form of a java command:

java -enableassertions MyClassName
  or
java -ea MyClassName

then when the process encounters the keyword assert as in the form:

assert([boolean expression]);
    as in the example:
assert(a+b>c);

then if the expression evaluates to false it prints a diagnostic message and aborts the program. The diagnostic message is as follows:

assertion failed in file
   <name> in line <num>

However if the expression evaluates to true nothing happens and the program continues on.

You can also specify some packages and classes to enable assertions on and others to not do so. The following are examples:

This enables assertions in mypackage package 
and any subpackages of mypackage:
   java -ea:mypackage... MyClassName
   
This enables assertions only in the class mypackage.MySpecificClass
   java -ea:mypackage.MySpecificClass MyClassName   
   
This enables assertions in all classes of mypackage
package and any subpackages of mypackage
except mypackage.MySpecificClass
   java -ea:mypackage... -da:mypackage.MySpecificClass MyClassName

The switches -ea and -enableassertions are interchangeable. Also, the swiches -da and -disableassertions are interchangeable. If these switches have no argument, all the classes are effected except the system classes. To effect the system classes you can use the switches: -enablesystemassertions or -esa. To disable system class assertions you can use the switches -disablesystemassertions or -dsa. The "..." indicates you include all subpackages.

To set the assertions programmatically, you can use the methods:

public void clearClassAssertionStatus()
public void setClassAssertionStatus(String className, boolean enabled)
public void setDefaultAssertionStatus(boolean enabled) 
public void setPackageAssertionStatus(String packageName, boolean enabled)
of the java.lang.ClassLoader class.

The -ea, -da, -esa, and -dsa swiches in the java command work by using those ClassLoader methods.

*OracleTM and JavaTM are registered trademarks of Oracle and or its affiliates. Other names may be trademarks of their respective owners.*