Java Reference
In-Depth Information
SR 6.4
Transform the following nested if statement into an equivalent
switch statement.
if (num1 == 5)
myChar = 'W';
else
if (num1 == 6)
myChar = 'X';
else
if (num1 == 7)
myChar = 'Y';
else
myChar = 'Z';
6.2 The Conditional Operator
The Java conditional operator is similar to an if-else statement in some ways. It
is a ternary operator because it requires three operands. The symbol for the con-
ditional operator is usually written ?: , but it is not like other operators in that the
two symbols that make it up are always separated. The following is an example
of an expression that contains the conditional operator:
(total > MAX) ? total + 1 : total * 2;
Preceding the ? is a boolean condition. Following the ? are two expressions sepa-
rated by the : symbol. The entire conditional expression returns the value of the
first expression if the condition is true, and returns the value of the second expres-
sion if the condition is false.
Keep in mind that this example is an expression that returns a
value. The conditional operator is just that, an operator, not a state-
ment that stands on its own. Usually we want to do something with
that value, such as assign it to a variable:
KEY CONCEPT
The conditional operator evaluates to
one of two possible values based on
a boolean condition.
total = (total > MAX) ? total + 1 : total * 2;
The distinction between the conditional operator and a conditional statement
can be subtle. In many ways, the ?: operator lets us form succinct logic that serves
as an abbreviated if-else statement. The previous statement is functionally
equivalent to, but sometimes more convenient than, the following:
if (total > MAX)
total = total + 1;
else
total = total * 2;
 
Search WWH ::




Custom Search