The assert Keyword

Amazing as it may seem engineers and programmers can make mistakes, the assertion keyword is designed to help detect these. Assertions also aid program maintainers by making it clear what the original coder had in mind.

If assertions are enabled at run time each time the assertion statement is encountered by the JVM its associated conditional is tested. If the test returns false the program terminates and an error message is produced. If, on the other hand, the test returns true no special action is take. So, by using the assert statement we are stating a condition that we belive should always be true if our program behaves as we expect.

Assertions have the following advantages:

  • They can detect errors early in the development cycle. Typically the first time a program is run it will produce assertion errors and so alert the coder.
  • Normal comments tend not to be updated as a program evolves. Assertions have more teeth, they have to be updated as the code base changes.
  • Typically, when used correctly, assertions don't slow the program appreciably if they are disabled.
  • In Java the assertion statements are not eliminated from the production code. They are simply disabled at runtime. They can be enabled in the "field" if necessary. This contrasts with the assertion mechanism used in c and c plus plus.

Forms of the assert Statement in Java

There are two forms of the assert statement these are:
assert boolean expression; 
assert boolean expression : non-void expression;
The first of these is demonstrated in the next listing. In the second form the non-void expression is passed as the argument to a AssertionError exception. The second listing on this page shows this form of assert.

Example of the assert Statement in Java

In the next program the coder wanted to show all but the last argument to program.
/**
*Example of Java assertions
*/


class  AssertionsInJava
{
 
public static  void main(String[] args)
  {
   
//We want to print all but the last argument.
    //This is correct.
   
for (int i=0;i<args.length-1;i++)
    {
     
assert(i+1<args.length);
      System.out.println
("arg is: "+args[i]);
   
}

   
//We want to print all but the last argument.
    //There is a bug in the for statement.
   
for (int i=0;i<=args.length-1;i++)
    {
     
assert(i+1<args.length);
      System.out.println
("arg is: "+args[i]);
   
}
  }
}

To enable assertions at run time use the -ea option to the java VM. So, to compile and run from the command line use:
$
$ 
$ javac  AssertionsInJava.java
$ java -ea AssertionsInJava one two 
arg is: one
arg is: one
Exception in thread "main" java.lang.AssertionError
        at AssertionsInJava.main(AssertionsInJava.java:22)
$ 
To disable assertions use the -da option and this is in fact the default.
$ java -da AssertionsInJava one two 
arg is: one
arg is: one
arg is: two
$ java  AssertionsInJava one two 
arg is: one
arg is: one
arg is: two
$ 
$

More Assertions in Java

Our next listing shows the second form of the assert statement. In this listing the programmer expects the modulus operator to alway provide a positive result. Unfortunately this is not the reality in Java.
/**
*Example of Java error test in Java. We demonstrate explicit testing, exceptions and  assertions.
*/

//There is a bug in this code. Try entering a negative odd argument.
class  AssertionsInJava2
{
 
public static  void main(String[] args)
  {
   
int iFirstArgument=0;

   
//We use explicit testing for simple errors that can reasonably
    //be anticipated by the programmer.
   
if (args.length != 1)
    {
     
System.err.println("Error expecting a single integer argument.");
      System.exit
(1);
   
}

   
//We use Exception testing for more difficult errors or where the programmer
    //can't easily detect the error.
   
try
   
{
     
iFirstArgument = Integer.parseInt(args[0]);
   
}
   
catch (NumberFormatException e)
    {
     
System.err.println("Error the argument was not an integer.");
      System.exit
(2);
   
}
   
   
int iRemainder = iFirstArgument % 2;

   
//We use asserts to spot errors in logic and other programming bugs.
    //These shouldn't occur in the release version.
   
assert ((iRemainder==0)||(iRemainder==1)):"Expecting the  remainder to be 0 or 1";
   
if (iRemainder==1)
    {
     
System.out.println("The remainder is 1 so the input must be odd.");
   
}
   
else
   
{
     
//Bug
     
System.out.println("The remainder not 1 so the input must be even.");
   
}
  }
}
$ javac  AssertionsInJava2.java
$ 
$ java  -ea AssertionsInJava2 -7
Exception in thread "main" java.lang.AssertionError: Expecting the  remainder to be 0 or 1
        at AssertionsInJava2.main(AssertionsInJava2.java:36)
$ 
$ java   AssertionsInJava2 -7
The remainder not 1 so the input must be even.
$ 

Where to use assertions

Assertions are used to detect design and programming bugs they are not used to handle normal program errors. Detecting and processing these errors is the role of exception handling or explicate error checking. You shouldn't attempt to handle assert conditions by catching AssertionError exceptions since asserts are not normal errors that can be recovered from, rather they signal the program has faulty logic and needs debugging.

Summary

  • The assert statement is used to help detect bugs.
  • You should assert the conditions you belive to be true.
  • Assertions are normally disabled at run time but can be enabled to aid debugging.
  • Assertions can't be ignored by program maintainers. This contrasts with program comments which are often not kept up to date.
  • You shouldn't attempt to handle assert conditions by catching AssertionError exceptions.


Custom Search

Tutorial
Java Keywords
Programming Terms
The entire content of this site is subject to copyright.