Java Reference
InDepth Information
effectively with them, there are two important concepts that need to be understood:
precedence
and
associativity
. These concepts—and the operators themselves—are
explained in more detail in the following sections.
Precedence
The P column of
Table 24
specifies the
precedence
of each operator. Precedence
specifies the order in which operations are performed. Operations that have higher
precedence are performed before those with lower precedence. For example, con‐
sider this expression:
a
x
a
+
b
*
c
The multiplication operator has higher precedence than the addition operator, so
a
is added to the product of
b
and
c
, just as we expect from elementary mathematics.
Operator precedence can be thought of as a measure of how tightly operators bind
to their operands. The higher the number, the more tightly they bind.
Default operator precedence can be overridden through the use of parentheses that
explicitly specify the order of operations. The previous expression can be rewritten
to specify that the addition should be performed before the multiplication:
(
a
+
b
)
*
c
The default operator precedence in Java was chosen for compatibility with C; the
designers of C chose this precedence so that most expressions can be written natu‐
rally without parentheses. There are only a few common Java idioms for which
parentheses are required. Examples include:
// Class cast combined with member access
((
Integer
)
o
).
intValue
();
// Assignment combined with comparison
while
((
line
=
in
.
readLine
())
!=
null
)
{
...
}
// Bitwise operators combined with comparison
if
((
flags
&
(
PUBLIC

PROTECTED
))
!=
0
)
{
...
}
Associativity
Associativity is a property of operators that defines how to evaluate expressions that
would otherwise be ambiguous. This is particularly important when an expression
involves several operators that have the same precedence.
Most operators are lefttoright associative, which means that the operations are
performed from left to right. The assignment and unary operators, however, have
righttoleft associativity. The A column of
Table 24
specifies the associativity of
each operator or group of operators. The value L means left to right, and R means
right to left.