24. Operator Precedence Hierarchy

 

Table E.1 summarizes the precedence and associativity relationships for Java op- erators. Within a single expression, an operator of order m would be evaluated be- fore an operator of order n if m < n. Operators having the same order are evaluated according to their association order. For example, the expression

,,

 

J

would be evaluated in the order shown by the following parenthesized expression:

,,

 

J

In other words, because * has higher precedence than +, the multiplication op- eration 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:

,,

 

J

In this case, each variable will be assigned 100 as its value. But it’s important that this expression be evaluated from right to left. First, k is assigned 100. Then its value is assigned to j. And finally j’s value is assigned to i.

For expressions containing mixed operators, it’s always a good idea to use parentheses to clarify the order of evaluation. This will also help avoid subtle syntax and semantic errors.

 

 

 

 

 

 

 

 

823

 

824APPENDIXE Operator Precedence Hierarchy

 

 

 

 

 

 

 

 

 

TABLE E.1 Java operator precedence and associativity table.

OrderOperatorOperationAssociation

0( )Parentheses

1++--Postincrement, Postdecrement, Dot OperatorL to R

2++-- + - ! Preincrement, Predecrement,R to L

Unary plus, Unary minus, Boolean NOT

(type) newType Cast, Object InstantiationR to L

* / %Multiplication, Division, ModulusL to R

5+ - +Addition, Subtraction, String ConcatenationL to R

6< > <= >=Relational OperatorsL to R

7==!=Equality OperatorsL to R

Boolean XORL to R

&&Boolean ANDL to R

——Boolean ORL to R

11= += -= *= /= %= Assignment OperatorsR to L

 

 

 

 

 

 

 

 

 

Appendix F