Playing with HTMLTopShort-Circuit Evaluation

Short-Circuit Evaluation

In your lab this week, many of you will be tempted to write code that looks like this:

  if (field.containsSnake(position) || field.outOfBounds(position)) {
    ....
  }

to determine if the snake should die.

Unfortunately, if you write this, your program will (most likely) produce an ArrayIndexOutOfBoundsException as soon as your snake hits the wall.

Changing this to:

  if (field.outOfBounds(position) || field.containsSnake(position)) {
    ....
  }

fixes the problem, since Java tries to do as little work as possible when evaluating boolean expressions. For an "or" expression, Java can determine that the value is true as soon as it finds one subexpression that is true. For an "and", the value can be determined to be false as soon as any subexpression evaluates to false.

So in the above example, if the outOfBounds method returns true, the containsSnake method is never called, thereby averting the ArrayIndexOutOfBoundsException. This is called short circuit evaluation.

Another common way to take advantage of this feature is to check that an object is not null before calling a method on that object:

   if (obj != null && obj.someMethod(...)) {...}

Playing with HTMLTopShort-Circuit Evaluation