Java Reference
In-Depth Information
Self-Test Exercises
(continued)
10. What is the output produced by the following code?
int
key = 1;
switch
(key + 1)
{
case
1:
System.out.println("Apples");
break
;
case
2:
System.out.println("Oranges");
break
;
case
3:
System.out.println("Peaches");
case
4:
System.out.println("Plums");
break
;
default
:
System.out.println("Fruitless");
}
11. What would be the output in Exercise 10 if the fi rst line were changed to the
following?
int
key = 3;
12. What would be the output in Exercise 10 if the fi rst line were changed to the
following?
int
key = 5;
The Conditional Operator
★
You can embed a branch inside of an expression by using a ternary operator known
as the
conditional operator
(also called the
ternary operator
or
arithmetic
if
).
Its use is reminiscent of an older programming style, and we do not advise using it.
It is included here for the sake of completeness (and in case you disagree with our
programming style).
The conditional operator is a notational variant on certain forms of the
if-else
statement. The following example illustrates the conditional operator. Consider the
following
if-else
statement:
conditional
operator
ternary
operator
arithmetic
if
if
(n1 > n2)
max = n1;
else
max = n2;