1️⃣

7.1 Switch

Chapter Table of Contents

⚒️
Ch. 7 Other Selection Structures

Section Table of Contents

 
Besides if statements, there are also 2 other selection structures you should know about: switch and ternary operator.

Switch

Switch statements allow you to run different blocks of code depending on one variable. This is the general format of a switch statement:
switch (variable) { case 1: // do stuff case 2: // do stuff ... case n: // do stuff }
You can use a switch on a variable which is a char, byte, short, int, or String.
 

It's kind of like conditionals, so why switch? (pun intended)

Switch statements are a more elegant way of using an if-else chain. For example, if you wanted a user to choose from suppose four operations for a calculator, you would only be checking one variable, their choice. You could have them enter a 1 for addition, a 2 for subtraction, a 3 for multiplication, and a 4 for division. Depending on if their choice is 1, 2, 3, or 4, you’ll compute the result in a different way. Let’s look at an example of a basic calculator implemented with a switch statement.

Switch Example

public static void main(String[] args) { System.out.println("add | subtract | multiply | divide"); Scanner input = new Scanner(System.in); System.out.print("Enter an operation above: "); String operation = input.nextLine().toLowerCase(); // case insensitive input.close(); boolean isOperationValid = operation.equals("add") || operation.equals("subtract") || operation.equals("multiply") || operation.equals("divide"); if (isOperationValid) { System.out.print("Enter operand 1: "); double operand1 = input.nextDouble(); System.out.print("Enter operand 2: "); double operand2 = input.nextDouble(); double result = 0; // placeholder char operator = ' '; // placeholder switch (operation) { case "add": result = operand1 + operand2; operator = '+'; break; case "subtract": result = operand1 - operand2; operator = '-'; break; case "multiply": result = operand1 * operand2; operator = '*'; break; case "divide": result = operand1 / operand2; operator = '/'; break; } System.out.println( operand1 + " " + operator + " " + operand2 + " = " + result ); } else { System.out.println("Sorry, that is not a valid operation."); } }
 
Sample output:
add | subtract | multiply | divide Enter an operation above: divide Enter operand 1: 20 Enter operand 2: 4 20.0 / 4.0 = 5.0

Explanation

Here the switch variable is a String which is the operation from user input. Depending on what is inputted, the program performs the correct corresponding operation. If the user gives an invalid operation, an error message will print out instead.

Fall-Through Behavior

You may have noticed that at the end of each case’s code block was a line that said breakbreak is a keyword that allows you to stop a process from continuing. If we didn’t have the break statement, something called fall-through behavior would occur. Analyze the following code, which is an example of fall-through.
int n = 3; switch (n) { case 1: System.out.println(1); case 2: System.out.println(2); case 3: System.out.println(3); case 4: System.out.println(4); case 5: System.out.println(5); break; case 6: System.out.println(6); }
 
Output:
3 4 5
Notice that the program first looks for the case that matches the switch variable. In this case, since n == 3, the code inside of the case 3 block runs. However, since there is no break statement, it keeps going and executes the code from the subsequent cases until the switch ends, or a break statement is reached.
Long story short, make sure you put break statements! Of course, keep in mind that sometimes it is useful to fall-through. For example, if 3 of my cases have the same result, I don’t need to write the same code block 3 times.
A real life application of fall-through is phone numbers. You may have seen on a phone keypad that usually 3-4 letters are associated with a number. If we wanted to translate a phone word to a phone number (you may have seen advertisements where the phone number is a word, like 1-800-GOT-JUNK), we could do so with a switch statement:
 
char ch = 'a'; int number = 0; switch (ch) { case 'a': case 'b': case 'c': number = 2; break; case 'd': case 'e': case 'f': number = 3; break; case 'g': case 'h': case 'i': number = 4; break; case 'j': case 'k': case 'l': number = 5; break; case 'm': case 'n': case 'o': number = 6; break; case 'p': case 'q': case 'r': case 's': number = 7; break; case 't': case 'u': case 'v': number = 8; break; case 'w': case 'x': case 'y': case 'z': number = 9; break; // technically not needed, but good practice in case you add more cases later
 

Default

Switch statements can also handle default cases using the default keyword. This is a little bit like the final else block in an if-else chain. Analyze the code below.
switch (choice) { case 1: System.out.println("May the Force be with you."); break; case 2: System.out.println("Tahiti, it's a magical place."); break; case 3: System.out.println("Live long and prosper."); break; case 4: System.out.println("No mourners, no funerals."); break; default: System.out.println("Error, invalid greeting number."); }
 
Sample output 1:
Greetings: (1) Star Wars (2) Agents of SHIELD (3) Star Trek (4) Six of Crows Which greeting do you want? 2 Tahiti, it's a magical place.
 
Sample output 2:
Greetings: (1) Star Wars (2) Agents of SHIELD (3) Star Trek (4) Six of Crows Which greeting do you want? 0 Error, invalid greeting number
 
As you can see from the code and sample output, in the 2nd run of the program, the default block was used since the user inputted a number that didn’t fit any of the specified cases.

Next Section

2️⃣
7.2 Ternary Operator
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.