Java Reference
In-Depth Information
The result of this conditional expression is
expression1
if
boolean-expression
is true;
otherwise the result is
expression2
.
Suppose you want to assign the larger number of variable
num1
and
num2
to
max
. You can
simply write a statement using the conditional expression:
max = (num1 > num2) ? num1 : num2;
For another example, the following statement displays the message “num is even” if
num
is
even, and otherwise displays “num is odd.”
System.out.println((num %
2
==
0
) ?
"num is even"
:
"num is odd"
);
As you can see from these examples, conditional expressions enable you to write short and
concise code.
Note
The symbols
?
and
:
appear together in a conditional expression. They form a condi-
tional operator called a
ternary operator
because it uses three operands. It is the only
ternary operator in Java.
3.33
✓
✓
Suppose that, when you run the following program, you enter input
2 3 6
from the
console. What is the output?
Check
Point
public class
Test {
public static void
main(String[] args) {
java.util.Scanner input =
new
java.util.Scanner(System.in);
double
x = input.nextDouble();
double
y = input.nextDouble();
double
z = input.nextDouble();
System.out.println((x < y && y < z) ?
"sorted"
:
"not sorted"
);
}
}
3.34
Rewrite the following
if
statements using the conditional operator.
if
(ages >=
16
)
ticketPrice =
20
;
else
ticketPrice =
10
;
if
(count %
10
==
0
)
System.out.print(count +
"\n"
);
else
System.out.print(count);
3.35
Rewrite the following conditional expressions using
if-else
statements.
a.
score = (x >
10
) ?
3
* scale :
4
* scale;
b.
tax = (income >
10000
) ? income *
0.2
: income *
0.17
+
1000
;
c.
System.out.println((number %
3
==
0
) ? i : j);
You can use the
System.out.printf
method to display formatted output on the console.
Often it is desirable to display numbers in a certain format. For example, the following code
computes interest, given the amount and the annual interest rate.
double
amount =
12618.98
;
double
interestRate =
0.0013
;
Key
Point