Java Reference
In-Depth Information
If the
logical_expression
evaluates as
true
, the result of the operation is the value of
expression1
,
and if
logical_expression
evaluates to
false
, the result is the value of
expression2
. Note that if
ex-
pression1
is evaluated because
logical_expression
is
true
, then
expression2
is not, and vice versa.
You can use the conditional operator in lots of circumstances, and one common application of it is to
control output, depending on the result of an expression or the value of a variable. You can vary a message
by selecting one text string or another depending on the condition specified.
TRY IT OUT: Conditional Plurals
Type in the following code, which adds the correct ending to
'hat'
depending on how many hats you
have:
public class ConditionalOp {
public static void main(String[] args) {
int nHats = 1; // Number of hats
System.out.println("I have " + nHats + " hat" + (nHats == 1 ? "."
: "s."));
nHats++; // Increment number of hats
System.out.println("I have " + nHats + " hat" + (nHats == 1 ? "."
: "s."));
}
}
ConditionalOp.java
The output from this program is the following:
I have 1 hat.
I have 2 hats.
How It Works
The result of executing the conditional operator in the program is a string containing just a period when
the value of
nHats
is 1, and a string containing an
s
followed by a period in all other cases. The effect
of this is to cause the output statement to automatically adjust the output between singular and plural.
You can use the same technique in other situations, such as where you need to choose “he” or “she” for
example, as long as you are able to specify a logical expression to differentiate the situation in which
you should use one rather than the other. A more challenging application you could try is to append “st,”
“nd,” “rd,” or “th” to a date value, such as in “3rd November” or “4th July.”
THE SWITCH STATEMENT