Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: tweaked a bit

...

The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.

On the other hand, JLS Section 15.7.3 "Evaluation Respects Parentheses and Precedence" statesadds:

Java programming language implementations must respect the order of evaluation as indicated explicitly by parentheses and implicitly by operator precedence.

...

It is recommended that any expression should never write to memory that it subsequently reads, and it should never write to any memory twice. Memory writing and reading can occur directly in the expression from assignments , or indirectly through side-effects in functions called in the expression.

Noncompliant Code Example (

...

Order of

...

Evaluation)

This noncompliant code example shows how side-effects in expressions can lead to unanticipated outcomes. The programmer intends to write access control logic based on different threshold levels. Each user has a rating that must be above the threshold to be granted access. As shown, a simple function can calculate the rating. The get() method is expected to return a non-zero factor for users who are authorized, and a zero value for those who are unauthorized.

...

Code Block
bgColor#FFcccc
class BadPrecedence {
  public static void main(String[] args) {
    int number = 17;
    int[] threshold = new int[20];
    threshold[0] = 10;
    number = (number > threshold[0]? 0 : -2) + ((31 * ++number) * (number = get()));
    // ... 
    if(number == 0) {
      System.out.println("Access granted");
    } else {
      System.out.println("Denied access"); // number = -2
    }
  }
  public static int get() {
    int number = 0;
    // Assign number to non zero value if authorized else 0
    return number;
  }
}

Noncompliant Code Example (

...

Order of

...

Evaluation)

This noncompliant code example reorders the previous expression so that the left-to-right evaluation order of the operands corresponds with the programmer's intent.

...

Although this code performs as expected, it still represents poor practice, by writing to number three times in a single expression.

Compliant Solution (order of evaluation)

...

Code Block
bgColor#ccccff
final int authnum = get();
number = ((31 * (number + 1)) * authnum) + (authnum > threshold[0]? 0 : -2);

Exceptions

EXP09:EX1: The postincrement postfix increment and postdecrement postfix decrement operators (++ and --) assign a new value to a variable and then subsequently read it. These are well-understood and are an exception to the rule against reading memory that was written in the same expression.

...