Java Reference
In-Depth Information
TABLE 2.6
Operator Precedence
Operator Notes
. [] ()
Parentheses (“()”) are used to group expressions; a period (“.”) is
used for access to methods and variables within objects and
classes (discussed tomorrow); square brackets (“[]”) are used for
arrays. (This operator is discussed later in the week.)
++ — ! ~ instanceof
The
instanceof
operator returns
true
or
false
based on whether
the object is an instance of the named class or any of that class's
subclasses (discussed tomorrow).
new (
type
)
expression
The
new
operator is used for creating new instances of classes;
“()” in this case are for casting a value to another type. (You learn
about both of these tomorrow.)
Multiplication, division, modulus.
* / %
Addition, subtraction.
+ -
Bitwise left and right shift.
<< >> >>>
Relational comparison tests.
< > <= >=
Equality.
== !=
&
AND
^
XOR
|
OR
Logical
AND
&&
Logical
OR
||
Shorthand for
if
-
then
-
else
(discussed on Day 5).
? :
Various assignments.
= += -= *= /= %= ^=
More assignments.
&= |= <<= >>= >>>=
Returning to the expression
y = 6 + 4 / 2
, Table 2.6 shows that division is evaluated
before addition, so the value of
y
will be
8
.
To change the order in which expressions are evaluated, place parentheses around the
expressions that should be evaluated first. You can nest one set of parentheses inside
another to make sure that expressions are evaluated in the desired order; the innermost
parenthetic expression is evaluated first.
The following expression results in a value of
5
:
y = (6 + 4) / 2
The value of
5
is the result because
6 + 4
is calculated first, and then the result, 10, is
divided by 2.