Classes/Objects  «Prev 


The Precedence program

The Precedence program provides an example of how to use precedence and associativity to evaluate a complex expression.
The result displayed by the program is 107.
At first glance, the following expression may seem daunting.
s = s += i = b ? 1 + 2 * i++ : --i;

However, if you evaluate it step by step, you will be able to quickly and methodically arrive at the correct result.
The first thing that you should note is that the ternary operator is used. The ternary operator is a short-circuit operator, which means that its second and third operands will only be (conditionally) evaluated based on the result of the first operand. Since the ternary operator has higher precedence than the = and += operators, it is evaluated first.
Since b is true, the result returned by the ternary operator is 1 + 2 * i++. The ++ operator has a higher precedence than *, which has a higher precedence than +. The result returned by the ternary operator is 1 + (2 * (i++)), which is 1 + (2 * 3) or 7.
Substituting 7 in the overall expression, we now have:
					
s = s += i = 7;

The = and += operators have the same precedence, but they are right-associative. The expression is evaluated as:
					
s = (s += (i = 7));

which results in 7 being assigned to i, and appended to s. Since the value of s is "10" before the expression is evaluated, its final value is "107".

Precedence

public class Precedence {

  public static void main(String[] args) {
    String s = "10";
    int i = 3;
    boolean b = true;
    s = s += i = b ? 1 + 2 * i++ : --i;    
    System.out.println(s);
  }
}