Switch case
Published: (February 7, 2026 at 04:44 AM EST)
2 min read
Source: Dev.to
Source: Dev.to
Overview
- A switch case is a control statement that lets you run different blocks of code based on the value of a variable or expression.
- It is often cleaner and easier to read than writing many
if–elsestatements. - In Java, the
switchstatement works with primitive typesint,byte,short,charand, since Java 8, withString. - Starting with Java 12, the arrow syntax (
->) can be used as a more concise alternative tobreak.
Syntax
switch (expression) {
case value1:
// statements
break; // stops fall‑through
case value2 -> // arrow syntax (Java 12+)
// statements
default:
// default statements
}
break;stops execution after the matched case block.- Arrow syntax (
->) automatically prevents fall‑through, so an explicitbreakis not needed.
Example 1 – Switching on an int
public class SwitchCaseExample {
public static void main(String[] args) {
int day = 5; // can be int, byte, short, or char
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Holiday");
}
}
}
Example 2 – Switching on a String (Java 8+)
package moduleTwo;
public class SwitchCaseTest {
public static void main(String[] args) {
String say = "hello";
switch (say) {
case "hi":
System.out.println("hey");
break;
case "hello":
System.out.println("Good morning");
break;
default:
System.out.println("unknown");
}
}
}
Example 3 – Multiple Labels and Arrow Syntax (Java 12+)
public class SwitchCaseTest {
public static void main(String[] args) {
String grade = "B";
switch (grade) {
case "A", "B" -> System.out.println("pass");
case "C" -> System.out.println("fail");
default -> System.out.println("no result");
}
}
}