Java switch Statement Tutorial with Examples
Introduction
When a decision depends on one variable having one of several fixed values - a day of the week, a menu choice, a command - a long
(Note - This tutorial follows Java if, else if and else StatementsClick to read tutorial: Java if, else if and else Statements with Examples.) Syntax of the switch statement
Where,
OUTPUT of the above code
break and fall-through
The
OUTPUT of the above code
Execution entered at
OUTPUT of the above code
Switching on strings and enums
A switch works with these types -
OUTPUT of the above code
Explanation of the code
else if ladder becomes repetitive. The switch statement handles this case more clearly. This tutorial explains the classic Java switch statement with examples. We will start with its syntax and how it chooses a case. We will then understand break and fall-through, and use fall-through on purpose to group cases. Next we will switch on strings and enums, and look at the types switch accepts. Lastly, we will go through common mistakes, and see when to use the newer switch expressionsClick to read tutorial: Java Switch Expressions: Arrow Labels and yield instead.(Note - This tutorial follows Java if, else if and else StatementsClick to read tutorial: Java if, else if and else Statements with Examples.) Syntax of the switch statement
Syntax of the classic switch statement
switch (expression) {
case value1:
statements
break;
case value2:
statements
break;
default:
statements
}
expressionis evaluated once, and its value is compared with eachcaselabel.- Execution jumps to the matching
caseand runs its statements.breakthen exits theswitch. defaultruns when nocasematches. It is optional, and is usually written last.- Each
casevalue must be a constant - a literal, afinalconstant or an enum constant - and no two cases can have the same value.
A simple switch statement
//DayName.java
public class DayName {
static String dayName(int day) {
String name;
switch (day) {
case 1:
name = "Monday";
break;
case 2:
name = "Tuesday";
break;
case 3:
name = "Wednesday";
break;
case 4:
name = "Thursday";
break;
case 5:
name = "Friday";
break;
case 6:
name = "Saturday";
break;
case 7:
name = "Sunday";
break;
default:
name = "Invalid day";
}
return name;
}
public static void main(String[] args) {
System.out.println("3 -> " + dayName(3));
System.out.println("7 -> " + dayName(7));
System.out.println("9 -> " + dayName(9));
}
}
3 -> Wednesday 7 -> Sunday 9 -> Invalid day
case labels are only entry points. Once execution has jumped to a matching case, it keeps running the statements below it - including the statements of the following cases - until it reaches a break or the end of the switch. This is called fall-through. Forgetting a break is the most common switch bug -
A missing break causes fall-through
//FallThroughBug.java
public class FallThroughBug {
public static void main(String[] args) {
int level = 2;
switch (level) {
case 1:
System.out.println("Level 1: Beginner");
case 2:
System.out.println("Level 2: Intermediate");
case 3:
System.out.println("Level 3: Advanced");
default:
System.out.println("Unknown level");
}
}
}
Level 2: Intermediate Level 3: Advanced Unknown level
case 2, and with no break statements it fell through every case below it, including default.
Using fall-through to group cases
Fall-through is useful when several values should run the same code. Stack their case labels with no statements between them. A single case can also list several values, separated by commas, since Java 14.
Grouping cases that share code
//DaysInMonth.java
public class DaysInMonth {
static int daysIn(int month, boolean leapYear) {
int days;
switch (month) {
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
case 2:
days = leapYear ? 29 : 28;
break;
case 1, 3, 5, 7, 8, 10, 12: // several values in one case (Java 14+)
days = 31;
break;
default:
days = -1;
}
return days;
}
public static void main(String[] args) {
System.out.println("April : " + daysIn(4, false));
System.out.println("February : " + daysIn(2, true));
System.out.println("October : " + daysIn(10, false));
}
}
April : 30 February : 29 October : 31
int,short,byteandchar, and their wrapper classes;String(since Java 7) - compared withequals(), so the match is case-sensitive;- enum types - the case labels use the constant names without the enum's name, such as
case SATURDAY.
long, float, double and boolean cannot be switched on in a classic switch.
Switching on a String and an enum
//CommandSwitch.java
public class CommandSwitch {
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
public static void main(String[] args) {
String command = "stop";
switch (command.toLowerCase()) {
case "start":
System.out.println("Starting the engine");
break;
case "stop":
System.out.println("Stopping the engine");
break;
default:
System.out.println("Unknown command: " + command);
}
Day today = Day.SATURDAY;
switch (today) {
case SATURDAY:
case SUNDAY:
System.out.println(today + " is a weekend day");
break;
default:
System.out.println(today + " is a weekday");
}
}
}
Stopping the engine SATURDAY is a weekend day
command.toLowerCase()makes the match case-insensitive, so"STOP"would also match"stop".- Switching on a
nullString or enum throws aNullPointerExceptionin a classic switch, so make sure the value is notnull. - Enums are a natural fit for switch. You can read more about them in The Complete Java Enums TutorialClick to read tutorial on Java Enums.
- Missing break: end every case with
break(orreturn), unless you mean to fall through. If you do, add a// fall throughcomment so readers know it is deliberate. - Duplicate or non-constant case values: both are compile errors. A case label cannot be a variable.
- Variables shared between cases: all cases share one block, so a variable declared in one case is visible - but not initialized - in the cases after it. Wrap a case's statements in braces
{ }to give it its own scope. - Always include default, even if it only reports an unexpected value. It catches values you did not anticipate.
- Consider a switch expression: since Java 14, switch with arrow labels (
case 1 ->) never falls through, can return a value, and is checked for missing cases. It is the better choice for most new code.
case matching a value, and runs default when none matches. We then saw how a missing break causes fall-through, and used fall-through on purpose to group cases, along with comma-separated case values. Next we switched on strings and enums, and listed the types a switch accepts. Lastly, we went through common mistakes and best practices. In the next tutorial, we will look at the modern switch expressions with arrow labels and yieldClick to read tutorial: Java Switch Expressions: Arrow Labels and yield.Java Fundamentals Tutorials
Java if, else if and else Statements with ExamplesClick to read tutorial: Java if, else if and else Statements with Examples Java Switch Expressions: Arrow Labels and yieldClick to read tutorial: Java Switch Expressions: Arrow Labels and yield Java for Loop Tutorial with ExamplesClick to read tutorial: Java for Loop Tutorial with Examples Java while and do-while Loops with ExamplesClick to read tutorial: Java while and do-while Loops with Examples Java Enhanced for Loop (for-each) with ExamplesClick to read tutorial: Java Enhanced for Loop (for-each) with Examples Java break, continue and Labeled Loops ExplainedClick to read tutorial: Java break, continue and Labeled Loops Explained What is Java? History, Features, Editions and UsesClick to read tutorial: What is Java? History, Features, Editions and Uses
Java if, else if and else Statements with ExamplesClick to read tutorial: Java if, else if and else Statements with Examples Java Switch Expressions: Arrow Labels and yieldClick to read tutorial: Java Switch Expressions: Arrow Labels and yield Java for Loop Tutorial with ExamplesClick to read tutorial: Java for Loop Tutorial with Examples Java while and do-while Loops with ExamplesClick to read tutorial: Java while and do-while Loops with Examples Java Enhanced for Loop (for-each) with ExamplesClick to read tutorial: Java Enhanced for Loop (for-each) with Examples Java break, continue and Labeled Loops ExplainedClick to read tutorial: Java break, continue and Labeled Loops Explained What is Java? History, Features, Editions and UsesClick to read tutorial: What is Java? History, Features, Editions and Uses