3.1 Precedence and Associativity Rules for Operators

Precedence and associativity rules are necessary for deterministic evaluation of expressions. The operators are summarized in Table 3.1. They are discussed in subsequent sections in this chapter.

The following remarks apply to Table 3.1:

  • The operators are shown with decreasing precedence from the top of the table.

  • Operators within the same row have the same precedence.

  • Parentheses, ( ), can be used to override precedence and associativity.

  • The unary operators, which require one operand, include the postfix increment (++) and decrement (--) operators from the first row, all the prefix operators (+, -, ++, --, ~, !) in the second row, and the prefix operators (object creation operator new, cast operator (type)) in the third row.

  • The conditional operator (? :) is ternary, that is, requires three operands.

  • All operators not listed above as unary or ternary, are binary, that is, require two operands.

  • All binary operators, except for the relational and assignment operators, associate from left to right. The relational operators are nonassociative.

  • Except for unary postfix increment and decrement operators, all unary operators, all assignment operators, and the ternary conditional operator associate from right to left.

Table 3.1. Operator Summary

Postfix operators

[] . (parameters) expression++ expression--

Unary prefix operators

++expression --expression +expression -expression ~ !

Unary prefix creation and cast

new (type)

Multiplicative

* / %

Additive

+ -

Shift

<< >> >>>

Relational

< <= > >= instanceof

Equality

== !=

Bitwise/logical AND

&

Bitwise/logical XOR

^

Bitwise/logical OR

|

Conditional AND

&&

Conditional OR

||

Conditional

?:

Assignment

= += -= *= /= %= <<= >>= >>>= &= ^= |=

Precedence rules are used to determine which operator should be applied first if there are two operators with different precedence, and these follow each other in the expression. In such a case, the operator with the highest precedence is applied first.

2 + 3 * 4 is evaluated as 2 + (3 * 4) (with the result 14) since * has higher precedence than +.

Associativity rules are used to determine which operator should be applied first if there are two operators with the same precedence, and these follow each other in the expression.

Left associativity implies grouping from left to right:

1 + 2 - 3 is interpreted as ((1 + 2) - 3), since the binary operators + and - both have same precedence and left associativity.

Right associativity implies grouping from right to left:

- - 4 is interpreted as (- (- 4)) (with the result 4), since the unary operator - has right associativity.

The precedence and associativity rules together determine the evaluation order of the operators.



     
    ASPTreeView.com
     
    Evaluation has ґМДФФ·СЦЧЙexpired.
    Info...