Java Reference
In-Depth Information
Table 3.1
Arithmetic and logical Java operators in order of precedence
Operators
Explanation
[] .
array indexing, member reference
- ++ -- ! ~
unary operators: negate, increment, decrement, logical-not, bitwise-not
(
type
) new
coercion, or casting to a different type; creating a new object
* / %
multiplication, division, remainder
+ -
addition, subtraction
<< >> >>>
shift-left, shift-right-sign-extend, shift-right-zero-fill
< > <= >=
instanceof
less-than, greater-than, less-or-equal, greater-or-equal, comparing object
types
== !=
equal, not-equal
&
bitwise-and (boolean for boolean operands with no short-circuit)
*
^
bitwise-xor (with boolean operands it is a boolean-xor)
**
|
bitwise-or (boolean for boolean operands with no short-circuit)
*
&&
logical-and (with short-circuit)
*
||
logical-or (with short-circuit)
*
?:
Inline
if
expression, e.g.,
a ? b : c
says, if
a
is
true
, then the value
is
b
, else it is
c
.
= += -= *= /=
%= <<= >>=
>>>= &= ^= |=
Assignment; those with an operator, as in
a op= b
will perform the
operation
a op b
then assign the result back to
a
.
In Java there are two ways to do a boolean AND operation: using
&
or
&&
. Remember that
for “a AND b”, if either is
false
, then the result is
false
. That means that if “a” is
false
, there is no need to evaluate “b” because it will not affect the result. Skipping the
evaluation of “b” in this case is called
short-circuiting
. Java will use short-circuit evaluation
when using the
&&
operator, but not
&
. The same applies to the OR operators
||
and
|
where Java can short-circuit on a
true
evaluation of the first operand for
||
. This is an
important distinction when “a” and “b” are not just simple variable references but rather
method calls or other complex expressions, especially ones with side effects.
*
XOR is exclusive or, where the result of “a XOR b” is
true
if “a” or “b” is
true
, but not
both. For bitwise operands, “a” and “b” refer here to bits in the operand; for boolean
operands it is the one value. Examples:
5^6
is
3
;
true^false
is
true
but
true^true
is
false
.
**