Java Reference
In-Depth Information
Table 2.5
(continued)
OPERATOR
SYNTAX
VALID DATA TYPES
Equal to
= =
byte, short, int, long, float, double,
char, boolean, references
Not equal to
! =
byte, short, int, long, float, double,
char, boolean, references
Instance of
instanceof
references
We will see the comparison operators used extensively in Chapter 3, “Con-
trol Structures.” The instanceof operator is discussed in Chapter 8, “Polymor-
phism and Abstraction.”
Boolean Operators
The Boolean operators are used for combining two or more Boolean expres-
sions into a single Boolean expression. The conditional operators and (&&) and
or (||) can be used to combine two Boolean expressions, whereas the bitwise
operators and (&), or (|), and exclusive or (^) can be used on both Boolean
expressions and integers.
The Boolean operators are discussed in detail in Chapter 3, “Control
Structures.”
Ternary Operator
Another carryover from C++ is the ternary operator. It is called the ternary
operator because it has three operands, and it is basically a shortcut mechanism
for writing an if/else control structure. The syntax is the following:
(boolean expression) ? x : y
The first part is a Boolean expression followed by a question mark. If the
Boolean expression is true, the x statement is executed. If the Boolean expres-
sion is false, the y statement is executed.
The ternary operator was demonstrated in the ArithmeticDemo program.
(x == 5) ? “yes” : “no”;
If x is 5, then “yes” is displayed, otherwise “no” is displayed. As you will see
in Chapter 3, “Control Structures,” this can be accomplished in a much less
elegant manner by using the following if/else statement:
Search WWH ::




Custom Search