creation or cast new (type)expr
multiplicative * / %
additive + -
shift << >> >>>
relational < > >= <= instanceof
equality == !=
AND &
exclusive OR ^
inclusive OR |
conditional AND &&
conditional OR ||
conditional ?:
assignment = += -= *= /= %= >>= <<= >>>= &= ^= |=
All binary operators except assignment operators are left-associative. Assignment is right-associative. In other
words, a=b=c is equivalent to a=(b=c), so it is convenient to chain assignments together. The conditional
operator ?: is right-associative.
Parentheses are often needed in expressions in which assignment is embedded in a boolean expression, or in
which bitwise operations are used. For an example of the former, examine the following code:
while ((v = stream.next()) != null)
processValue(v);
Assignment operators have lower precedence than equality operators; without the parentheses, it would be
equivalent to
while (v = (stream.next() != null)) // INVALID
processValue(v);
and probably not what you want. It is also likely to be invalid code since it would be valid only in the unusual
case in which v is boolean.
Many people find the precedence of the bitwise and logical operators &, ^, and | hard to remember. In
complex expressions you should parenthesize these operators for readability and to ensure correct precedence.
Our use of parentheses is sparsewe use them only when code seems otherwise unclear. Operator precedence is
part of the language and should be generally understood. Others inject parentheses liberally. Try not to use
parentheses everywherecode becomes illegible, looking like LISP with none of LISP's saving graces.
Exercise 9.4: Using what you've learned in this chapter but without writing code, figure out which of the
following expressions are invalid and what the type and values are of the valid expressions: