Table E.1 summarizes the precedence and associativity relationships for Java operators. Within a single expression, an operator of order m would be evaluated before an operator of order n if m < n. Operators having the same order are evaluated according to their association order. For example, the expression 25 + 5 * 2 + 3 would be evaluated in the order shown by the following parenthesized expression: (25 + (5 * 2)) + 3 ==> (25 + 10) + 3 ==> 35 + 3 ==> 38 In other words, because * has higher precedence than +, the multiplication operation is done before either of the addition operations. And because addition associates from left to right, addition operations are performed from left to right.
Most operators associate from left to right, but note that assignment operators associate from right to left. For example, consider the following code segment: int i, j, k; i = j = k = 100; // Equivalent to i = (j = (k = 100)); In this case, each variable will be assigned 100 as its value. But it is important that this expression be evaluated from right to left. First, k is assigned 100. Then it's value is assigned to j. And finally j's value is assigned to i. For expressions containing mixed operators, it is always a good idea to use parentheses to clarify the order of evaluation. This will also help avoid subtle syntax and semantic errors. |