Appendix E. Operator Precedence Hierarchy


[Page 830]

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.

Table E.1. Java operator precedence and associativity.

Order

Operator

Operation

Association

0

( )

Parentheses

 

1

++ -- ·

Postincrement, Postdecrement, Dot Operator

L to R

2

++ -- + - !

Preincrement, Predecrement

R to L

  

Unary plus, Unary minus, Boolean NOT

 

3

(type) new

Type Cast, Object Instantiation

R to L

4

* / %

Multiplication, Division, Modulus

L to R

5

+ - +

Addition, Subtraction, String Concatenation

L to R

6

< > <= >=

Relational Operators

L to R

7

== !=

Equality Operators

L to R

8

L

Boolean XOR

L to R

9

&&

Boolean AND

L to R

10

LL

Boolean OR

L to R

11

= += -= *= /= %=

Assignment Operators

R to L



[Page 831]

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.




Java, Java, Java(c) Object-Orienting Problem Solving
Java, Java, Java, Object-Oriented Problem Solving (3rd Edition)
ISBN: 0131474340
EAN: 2147483647
Year: 2005
Pages: 275

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net