Java Reference
In-Depth Information
flags
|=
f
;
// Set a flag f in an integer set of flags
flags
&=
~
f
;
// Clear a flag f in an integer set of flags
The Conditional Operator
The conditional operator
?
: is a somewhat obscure ternary (three-operand) opera‐
tor inherited from C. It allows you to embed a conditional within an expression.
You can think of it as the operator version of the
if/else
statement. The first and
second operands of the conditional operator are separated by a question mark (
?
)
while the second and third operands are separated by a colon (:). The first operand
must evaluate to a
boolean
value. The second and third operands can be of any
type, but they must be convertible to the same type.
The conditional operator starts by evaluating its first operand. If it is
true
, the oper‐
ator evaluates its second operand and uses that as the value of the expression. On
the other hand, if the first operand is
false
, the conditional operator evaluates and
returns its third operand. The conditional operator never evaluates both its second
and third operand, so be careful when using expressions with side effects with this
operator. Examples of this operator are:
int
max
=
(
x
>
y
)
?
x
:
y
;
String
name
=
(
name
!=
null
)
?
name
:
"unknown"
;
Note that the
?
: operator has lower precedence than all other operators except the
assignment operators, so parentheses are not usually necessary around the operands
of this operator. Many programmers find conditional expressions easier to read if
the first operand is placed within parentheses, however. This is especially true
because the conditional
if
statement always has its conditional expression written
within parentheses.
The instanceof Operator
The
instanceof
operator is intimately bound up with objects and the operation of
the Java type system. If this is your first look at Java, it may be preferable to skim
this definition and return to this section after you have a decent grasp of Java's
objects.
instanceof
requires an object or array value as its left operand and the name of a
reference type as its right operand. It evaluates to
true
if the object or array is an
instance
of the specified type; it returns
false
otherwise. If the left operand is
null
,
instanceof
always evaluates to
false
. If an
instanceof
expression evaluates to
true
, it means that you can safely cast and assign the left operand to a variable of
the type of the right operand.
The
instanceof
operator can be used only with reference types and objects, not
primitive types and values. Examples of
instanceof
are:
// True: all strings are instances of String
"string"
instanceof
String
// True: strings are also instances of Object