Learn Java · lesson 16 of 61 · about 8 minutes
switch
Price the snacks: choose between exact values with switch, use the arrow form that never falls through, and let a switch expression produce a value.
What you'll learn
- Write a classic switch with break
- Write an arrow switch
- Use a switch expression to produce a value
Two styles
The classic switch needs break to stop falling into the next case. Modern Java has an arrow form, case "popcorn" -> ..., which never falls through. One case can list several values, like case "drink", "soda" ->.
Unlike C and C++, Java's switch works with Strings, as well as whole numbers and chars.
Classic and arrow
public class Main {
public static void main(String[] args) {
char choice = 'b';
switch (choice) {
case 'a':
System.out.println("Start lesson");
break;
case 'b':
System.out.println("Open shop");
break;
default:
System.out.println("Unknown");
}
String cmd = "streak";
switch (cmd) {
case "shop" -> System.out.println("Opening shop");
case "streak", "fire" -> System.out.println("7 days!");
default -> System.out.println("Unknown command");
}
}
}Output
Open shop
7 days!A switch that gives a value
A switch expression works out a value, so it can sit on the right of =: int snackCents = switch (snack) { ... };. Each arrow gives the value for its case, and the whole thing ends with ; like any other statement. It must cover every possible value, so a switch on a String needs a default.
Pricing a snack
public class Main {
public static void main(String[] args) {
String snack = "soda";
int snackCents = switch (snack) {
case "popcorn" -> 450;
case "nachos" -> 600;
case "drink", "soda" -> 300;
default -> 0;
};
System.out.println("Snacks: " + snackCents + " cents");
}
}Output
Snacks: 300 centsTip
A switch compares exact values. For ranges like age < 12, use if / else if.
Now try it yourself
This lesson is free in Codiqo, with 11 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.