JMU
Assertions in Java
An Introduction


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Motivation
Overview
Syntax
Behavior of Assertions
Enabling and Disabling Assertions
Uses
An Example of an Internal Invariant

This fragment assumes i is non-negative.

  if (i > 0)
  {
    // Do something
  }
  else // We know i is equal to 0
  {
    // Do something
  }
  
An Example of an Internal Invariant (cont.)

One Approach:

  if (i > 0)
  {
    // Do something
  }
  else
  {
    assert i == 0 : i;
    // Do something
  }
  

Another Approach:

  assert i >= 0 : i;
  if (i > 0)
  {
    // Do something
  }
  else
  {
    // Do something
  }
  
A Concrete Example of an Internal Invariant

The Original Code Ignoring the Invariant:

  if (delta > 0) total += delta;
  

Alternative Code Ignoring the Invariant:

  total += Math.max(0, delta);
  

Taking Advantage of the Invariant Using an Assertion:

  assert delta >= 0 : delta;
  total += delta;
  
An Example of a Control-Flow Invariant

This fragment assumes that there are only four suits.

  switch(suit)
  {
    case Suit.CLUBS:
      // Do something
      break;

    case Suit.DIAMONDS:
      // Do something
      break;

    case Suit.HEARTS:
      // Do something
      break;

    case Suit.SPADES:
      // Do something
      break;

    default:
      // Shouldn't get here
  }
  
An Example of a Control-Flow Invariant (cont.)

Using an assertion

  switch(suit)
  {
    case Suit.CLUBS:
      // Do something
      break;

    case Suit.DIAMONDS:
      // Do something
      break;

    case Suit.HEARTS:
      // Do something
      break;

    case Suit.SPADES:
      // Do something
      break;

    default:
      assert false : suit;
  }
  
The Other Uses Explained