The Conditional Operator and the 'switch' Statement
Site: | Saylor Academy |
Course: | CS101: Introduction to Computer Science I |
Book: | The Conditional Operator and the 'switch' Statement |
Printed by: | Guest user |
Date: | Wednesday, May 14, 2025, 2:26 AM |
Description
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.
Table of contents
- 1. More Ways to Make Decisions
- 2. If-Else Absolute Value
- 3. Maximum and Minimum
- 4. More Complicated Expressions
- 5. Many-way Branches
- 6. Rules for switch Statements
- 7. Example
- 8. Flowchart of a break Statement
- 9. Using break
- 10. Corrected Program
- 11. Upper and Lower Case
- 12. if Statement Equivalent
- 13. Range Testing
- 14. switch with Strings
- 15. Example with Strings
- 16. End of Chapter
1. More Ways to Make Decisions
Nested if
and else
statements can be used to choose between any number of options. But, using nested statements is sometimes awkward. This chapter discusses two other statements that choose between several
options.
Neither of these two statements does anything that can't be done with if
s and else
s. But they are sometimes useful, and you will need to know them to understand programs written by other programmers.
Some programmers avoid using these statements. Neither statement is used in the AP Computer Science test. This entire chapter may be skipped. These statements are not used in the chapters that follow.
Chapter Topics:
- The conditional operator
?
- The
switch
statement
Question 1:
- What is the absolute value of -9?
- What is the absolute value of +9?
Source: Bradley Kjell, http://programmedlessons.org/Java9/chap34/ch34_01.html This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 License.
2. If-Else Absolute Value
Answer:
- What is the absolute value of -9?
- +9
- What is the absolute value of +9?
- +9
If-Else Absolute Value
Anif
statement can be used to compute absolute values:
if ( value < 0 )
abs = -value;
else
abs = value;
This is awkward for such a simple idea. The following does the same thing in one statement:
abs = (value < 0 )?
-value:
value ;
This statement uses a conditional operator. The right side of the =
is a conditional expression. The expression is evaluated to produce a value, which is then assigned to the variable, abs
.
The conditional operator is used in an expression. It asks for a value to be computed but does not by itself change any variable. In the example, the variable value
is not changed. Usually, an assignment operator
is used to make a change.
double value = -34.569; double abs; abs = (value < 0 ) |
The conditional operator is used like this:
true-or-false-condition?
value-if-true:
value-if-false
Here is how it works:
- The true-or-false-condition evaluates to true or false.
- That value selects one choice:
- If the true-or-false-condition is true, then evaluate the expression between
?
and:
- If the true-or-false-condition is false, then evaluate the expression between
:
and the end .
- If the true-or-false-condition is true, then evaluate the expression between
- The result of evaluation is the value given to the entire conditional expression.
Question 2:
Given
int a = 7, b = 21;
What is the value of:
a > b ?
a :
b
(Even though it looks funny, the entire expression stands for a single value.)
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.
4. More Complicated Expressions
Answer:
int a = 7, b = 21;
System.out.println( "The min is: " + (a < b ?
a :
b ) );
More Complicated Expressions
Here is a slightly more interesting example:
A program computes the average grade of each student in a class. Students whose average grade is below 60 are given a bonus of 5 points. All other students are given a bonus of just 3 points.
Here is the program fragment that does this:
... average grade is computed here ...
average += (average < 60 ) ? 5 : 3;
The subexpressions that make up a conditional expression can be as complicated as you want. Now say that grades below 60 are to be increased by 10 percent and that other grades are to be increased by 5 percent.
Here is the program fragment that does this:
... average grade is computed here ...
average +=
(average < 60 ) ? average*0.10 : average*0.05;
This is probably about as complicated as you want to get with the conditional operator. If you need to do something more complicated than this, do it with if-else
statements.
Question 4:
Write an assignment statement that adds one to the integer number
if it is odd, but adds nothing if it is even.
5. Many-way Branches
Answer:
number += (number % 2 == 1 ) ? 1 : 0 ;
Many-way Branches
Often a program needs to make a choice among several options based on the value of a single expression. For example, a clothing store might offer a discount that depends on the quality of the goods:
- Class 'A' goods are not discounted at all.
- Class 'B' goods are discounted 10%.
- Class 'C' goods are discounted 20%.
- anything else is discounted 30%.
The program fragment does that. A choice is made between four options based on the value in code
.
The switch
statement looks at the case
s to find a match for the value in code
.
It then executes the statements between the matching case
and the following break
. All other case
s are skipped. If there is no match, the default
case is chosen.
The default
case is optional. If present, it must be the last case.
Warning: the complete rules for switch
statements are complicated. Read on to get the details.
|
Question 5:
If code
is 'C', what is the discount?
6. Rules for switch Statements
Answer:
0.2
Rules for switch
Statements
switch
StatementsHere is what a switch statement looks like:
|
Here is how it works:
- Only one case is selected per execution of the
switch
statement. - The value of
expression
determines which case is selected. expression
must evaluate to byte, short, char, or int primitive data, aString
, or a few other types not discussed further here.- The type of
expression
and the type of thelabel
s must agree. - Each
label
must be an integer literal (like 0, 23, or 'A'), aString
literal (like "green"), but not an expression or variable. - There can be any number of statements in a
statementList
. - The
statementList
is usually followed withbreak;
- Each time the
switch
statement is executed, the following happens:- The
expression
is evaluated. - The
label
s after eachcase
are inspected one by one, starting with the first. - The first label that matches has its
statementList
execute. - The statements execute until a
break
statement is encountered. - Now the entire
switch
statement is complete (no further statements are executed.)
- The
- If no case label matches the value of
expression
, then thedefault
case is picked, and its statements execute. - If no case label matches the value of
expression
, and there is nodefault
case, no statements execute.
Question 6:
Could the type of the expression
be a float
or a double
?
7. Example
Answer:
No
Rules for switch
Statements
switch
StatementsWe will get to those other rules shortly. Here is the previous example, with more explanation:
double discount; char code = 'B' ; // Usually the value for code would come from data // or from user interaction switch ( code ) { case 'A': discount = 0.0; break; case 'B': discount = 0.1; break; case 'C': discount = 0.2; break; default: discount = 0.3; } System.out.println( "discount is: " + discount ); |
- The
expression
is evaluated.- In this example, the expression is the variable,
code
, which evaluates to the character 'B'.
- In this example, the expression is the variable,
- The case labels are inspected starting with the first.
- The first one that matches is
case 'B'
- The
statementList
aftercase 'B'
starts executing.- In this example, there is just one statement.
- The statement assigns 0.1 to
discount
.
- The
break
statement is encountered which ends thestatementList
. - The statement after the entire
switch
statement is executed.- In this example, that is the
println()
statement
- In this example, that is the
Question 7:
If code is 'W' what is discount?
8. Flowchart of a break Statement
Answer:
0.3
Flowchart of a break
Statement
break
StatementHere is the example program fragment (again) and a flowchart that shows how it works. The box in the flowchart "evaluate code" means to get the current value of code
. In a larger program this would usually be different every time.
Question 8:
(Trick Question:) What would be the discount if code
were 'a' ?
9. Using break
Answer:
0.3
Notice that the code is a lower case 'a', not upper case.
Using break
break
There is one label per case
statement, and there must be an exact match with the expression in the switch
for the case to be chosen.
The break
at the end of each case
is optional. If it is omitted, then after the statements in the selected case have executed, execution will continue with the following case. This
is not usually what you want.
The fragment will print:
Color is yellow green blue violet unknown
This is probably not what the program was intended to do.
Examine the following fragment:
class Switcher { public static void main ( String[] args ) { char color = 'Y' ; String message = "Color is"; switch ( color ) { case 'R': message = message + " red" ; case 'O': message = message + " orange" ; case 'Y': message = message + " yellow" ; case 'G': message = message + " green" ; case 'B': message = message + " blue" ; case 'V': message = message + " violet" ; default: message = message + " unknown" ; } System.out.println ( message ) ; } } |
Question 9:
Mentally fix the program fragment so that it prints just one color name.
10. Corrected Program
Answer:
The correct program fragment is given below.
Corrected Program
break
after the statement in the default case, but it is not needed.
class Switcher{ public static void main ( String[] args ) { char color = 'Y' ; String message = "Color is"; switch ( color ) { case 'R': message = message + " red" ; break; case 'O': message = message + " orange" ; break; case 'Y': message = message + " yellow" ; break; case 'G': message = message + " green" ; break; case 'B': message = message + " blue" ; break; case 'V': message = message + " violet" ; break; default: message = message + " unknown" ; } System.out.println ( message ) ; } } |
Often what you really want is for several characters to select a single case. This can be done using several case statements, followed by just one list of statements.
For example, here both 'y' and 'Y' select the same statement:
case 'y': case 'Y': message = message + " yellow" ; break;
Question 10:
Mentally insert extra case statements into the program so that upper and lower case
characters work for each color. (Or, even better: copy the program to an editor, fix it, and run it.)
11. Upper and Lower Case
Answer:
The completed program is given below.
Upper and Lower Case
The program has also been improved by accepting input from the user. The program uses the charAt( int index )
method of the String
class. This method returns a single character from a string.
The first character is at index 0, the next is at index 1, and so on. (Remember: a String
is an object, even if it contains only one character. The charAt()
method must be used here to get a char
that can be used in the switch
.)
import java.util.Scanner; class Switcher { public static void main ( String[] args ) { String lineIn; char color ; String message = "Color is"; Scanner scan = new Scanner( System.in ); System.out.print("Enter a color letter: "); lineIn = scan.nextLine(); color = lineIn.charAt( 0 ); // get the first character switch ( color ) { case 'r': case 'R': message = message + " red" ; break; case 'o': case 'O': message = message + " orange" ; break; case 'y': case 'Y': message = message + " yellow" ; break; case 'g': case 'G': message = message + " green" ; break; case 'b': case 'B': message = message + " blue" ; break; case 'v': case 'V': message = message + " violet" ; break; default: message = message + " unknown" ; } System.out.println ( message ) ; } } |
Question 11:
Could the above program be written using if
statements?
12. if Statement Equivalent
Answer:
Of course. Any switch
statement can be done with nested if
s .
if
Statement Equivalent
if
Statement Equivalent
if
statements, or if else if
statements (which are really the same thing.) Here is the previous program, rewritten with equivalent if else if
statements.
import java.util.Scanner; class Switcher { public static void main ( String[] args ) throws IOException { String lineIn; char color ; String message = "Color is"; Scanner scan = new Scanner( System.in ); System.out.println("Enter a color letter:"); lineIn = scan.nextLine(); color = lineIn.charAt( 0 ); // get the first character if ( color=='r' || color=='R' ) message = message + " red" ; else if ( color=='o' || color=='O' ) message = message + " orange" ; else if ( color=='y' || color=='Y' ) message = message + " yellow" ; else if ( color=='g' || color=='G' ) message = message + " green" ; else if ( color=='b' || color=='B' ) message = message + " blue" ; else if ( color=='v' || color=='V' ) message = message + " violet" ; else message = message + " unknown" ; System.out.println ( message ) ; } } |
Question 12:
Is the program correct? Is ==
being used correctly?
13. Range Testing
Answer:
There is nothing wrong with the program. Since color
is a primitive data type, an expression such as
color == 'V'
compares the contents of color (a character) to the character literal 'V'. However, the following is wrong:
color == "V"
This is asking to compare the primitive character value in color
with a reference to the String object "V".
Range Testing
Say that you have the following problem: Assign a Beaufort number to bNumber
based on wind speed in meters per second.
wind speed |
Beaufort number |
---|---|
0 - 0.3 |
0 |
0.3 - 1.6 |
1 |
1.6 - 3.4 |
2 |
3.4 - 5.5 |
3 |
5.5 - 8.0 |
4 |
8.0 - 10.8 |
5 |
10.8 - 13.9 |
6 |
13.9 - 17.2 |
7 |
17.2 - 20.8 |
8 |
20.8 - 24.5 |
9 |
24.5 - 28.5 |
10 |
28.5 - 32.7 |
11 |
>=32.7 |
12 |
Assume that the upper number in each range is not included.
Lots of cases! You would hope that the switch
statement would work for this. But it does not. Floating point values don't work with switch
statements. You need to use if
and else if
.
if ( speed < 0.3 ) bNumber = 0; else if ( speed < 1.6 ) bNumber = 1; else if ( speed < 3.4 ) bNumber = 2; else if ( speed < 5.5 ) bNumber = 3; else if ( speed < 8.0 ) bNumber = 4; else if ( speed < 10.8 ) bNumber = 5; else if ( speed < 13.9 ) bNumber = 6; else if ( speed < 17.2 ) bNumber = 7; else if ( speed < 20.8 ) bNumber = 8; else if ( speed < 24.5 ) bNumber = 9; else if ( speed < 28.5 ) bNumber = 10; else if ( speed < 32.7 ) bNumber = 11; else bNumber = 12; |
Question 13:
Could integer ranges be used with a switch
statement? Say that value
is expected to be in
the range 1..10 and you want three categories: 1 to 3, 4 to 7, 8 to 10.
14. switch with Strings
Answer:
This could be done with multiple case:
labels, but the result is awkward.
switch ( value )
{
case 1: case 2: case3:
do-something;
break;
case 4: case 5: case6: case 7:
do-something;
break;
case 8: case 9: case 10:
do-something;
break;
}
switch
with String
s
switch
with String
sswitch
statement:
switch ( expression ) { case label1: statementList1 break; case label2: statementList2 break; case label3: statementList3 break; . . . other cases like the above default: defaultStatementList } |
Starting with Java 7.0 the expression
can be a String
reference and the case
labels can be String
literals.
Matching of the expression
with the case
labels is done as if by String.equals()
.
Question 14:
Is "BTW".equals( " BTW ")
true or false?
15. Example with Strings
Answer:
"BTW".equals( " BTW ")
is false
Blank spaces matter in string comparison.
Example with Strings
import java.util.Scanner; public class StringSwitcher { public static void main ( String[] args ) { String phrase; char color ; String message = "Phrase is: "; Scanner scan = new Scanner( System.in ); System.out.print("Enter Acronym: "); phrase = scan.nextLine().trim().toUpperCase(); switch ( phrase ) { case "LOL": message = message + "Laugh Out Loud" ; break; case "BFF": message = message + "Best Friends Forever" ; break; case "SO": message = message + "Significant Other" ; break; case "THS": case "THKS": case "TX": message = message + "Thanks" ; break; default: message = message + "unknown" ; } System.out.println ( message ) ; } } |
Users might put spaces before or after the acronym. The function String.trim()
removes white space from both sides of a string.
Another problem is that users might enter upper or lower case. The function String.toUpperCase()
creates a string with all upper case.
Question 15:
Could the strings in the case
statements use punctuation?
16. End of Chapter
Answer:
Yes. Any string literal can be used.
End of Chapter
This is the end of the chapter. A strong case can be made for reviewing the following subjects.
- conditional operator The conditional operator.
- switch statement Syntax of the
switch
statement. - switch statement, example Example of the switch statement.
- switch statement, flowchart Flowchart of the switch statement.
- break statement Role of the
break
statment. - switch statement, labels Using several labels per group of statements.