next up previous
Next: Java Statements Up: Java Mechanics Previous: Java Expressions


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 -.


Finger Exercise 1.3.3.1: In the DrJava Interactions pane, try evaluating the following expressions:

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

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.


Finger Exercise 1.3.3.2: In the DrJava Interactions pane, try evaluating the following expressions:

72. - 30. - 12.
72. - (30. - 12.)


next up previous
Next: Java Statements Up: Java Mechanics Previous: Java Expressions
Corky Cartwright 2004-02-05