4.2 Precedence of Operations
Keywords: current

Next: 4.3 Java Statements Up: 4. Appendix: Java Mechanics Previous: 4.1.1 Java Expressions

#
4.2 Precedence of Operations

Since Java uses conventional infix notation for expressions it relies on the notion of precedence to determine how expressions like

> `12 * 5 + 10`

should be interpreted. The Java operations given in the preceding subsection are divided into the following precedence groups:

> prefix operators | `- !`
> multiplicative | `* / %`
> additive | `+ -`
> relational | `< > >= <=`
> equality | `== !=`
> logical and | `&&`
> logical or | `||`
> conditional | `?` ... `:`

from highest to lowest. A higher precedence operator has greater ``binding power''. For example, the expression

> `72. - 32. * 1.8`

is equivalent to

> `72. - (32. * 1.8)`

because `*` has higher precedence than infix `-`.

All of infix operators listed above are left-associative: when infix operators of equal precedence are chained together, the leftmost operator has precedence. For example,

> `72. - 30. - 12.`

is equivalent to

> `(72. - 30.) - 12.`

Parentheses can be used to override the built-in precedence and associativity of operators. Hence,

> `(72. - 32.) * 1.8`

equals `40*1.8`. Similarly,

> `72. - (30. - 12.)`

equals

> `72. - 18.`

It is a good idea to use parentheses if you have any doubts about the precedence relationship between consecutive operators. The judicious use of parentheses makes complex expressions easier to read.

Next: 4.3 Java Statements Up: 4. Appendix: Java Mechanics Previous: 4.1.1 Java Expressions