Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The bitwise AND and OR operators (& and |) do not exhibit this behavior. Like Similar to most other Java operators, they evaluate both operands: first the left operand and then the right. They return the same Boolean result as && and || respectively but can have different overall effects depending on the presence or absence of side effects in the second operand.

...

This noncompliant code example, derived from Flanagan [Flanagan 2005], has two variables, with no guarantees regarding their current values. The code must validate its data and then check whether array[i] is nonnegativea valid index.

Code Block
bgColor#ffcccc
int array[]; // may be null
int i;       // may be aan validinvalid index for array
if (array != null &
    i >= 0 & i < array.length &
    array[i] >= 0) {
  // handleuse array
} else {
  // handle error
}

...

This compliant solution mitigates the problem by using &&, which causes the conditional expression to terminate immediately if any of the conditions fail, thereby preventing a potentially invalid evaluationruntime exception.

Code Block
bgColor#ccccff
int array[]; // may be null
int i;       // may be aan validinvalid index for array
if (array != null &&
    i >= 0 & i < array.length &&
    array[i] >= 0) {
  // handle array
} else {
  // handle error
}

...

Code Block
bgColor#ccccff
int array[]; // may be null
int i;       // may be a valid index for array
if (data != null) {
  if (i >= 0 & i < data.length) {
    if (data[i] != -1) {
      // handleuse array
    } else {
      // handle error
    }
  } else {
    // handle error
  }
} else {
  // handle error
}

Nevertheless, this solution would be useful is preferable if the error-handling routines for each potential condition failure were different.

...