Read this chapter, which discusses the switch and '?' operators to write conditional statements. As you read this tutorial, you will learn that sometimes it is better to use a 'switch' statement when there are multiple choices to choose from. Under such conditions, an if/else structure can become very long, obscure, and difficult to comprehend. Once you have read the tutorial, you will understand the similarity of the logic used for the 'if/else' statement, '?', and 'switch' statements and how they can be used alternately.
3. Maximum and Minimum
Answer:
The expression is evaluated to 21.
Maximum and Minimum
int a = 7, b = 21;
a > b?
a:
b
The expression evaluates to the maximum of two values:
- The condition
a > b
is false, so - The part after the colon (
:
) is evaluated, to 21. - That value is given to the entire conditional expression.
(Usually such an expression is part of a longer statement that does something with the value.)
Here is a program fragment that prints the minimum of two variables.
int a = 7, b = 21;
System.out.println( "The min is: " + (a ______ b?
a:
b ) );
Other than the blank, the fragment is correct. The value of the conditional expression is used with the concatenation operator +
in the println()
statement.
Question 3:
Fill in the blank so that the fragment works correctly.