← Back to Core Java Course | Chapter 4: Control Flow | Lesson 4 of 9

Java switch Statement

Basic switch Statement

A switch statement compares one variable's value against a list of possible cases in sequence, which reads more cleanly than a long chain of else-if blocks all testing the exact same variable.

Example: Basic switch Statement

java
public class Main {
	public static void main(String[] args) {
		int day = 3;
		switch (day) {
			case 1: System.out.println("Monday"); break;
			case 2: System.out.println("Tuesday"); break;
			case 3: System.out.println("Wednesday"); break;
		}
	}
}

The Importance of break

Without a break at the end of a matching case, execution 'falls through' into the next case's code even if its own condition wasn't checked -- this is a frequent source of bugs for developers new to switch statements.

Example: The Importance of break

java
public class Main {
	public static void main(String[] args) {
		int day = 1;
		switch (day) {
			case 1: System.out.println("Monday");
			case 2: System.out.println("Tuesday"); break; // falls through from case 1
			case 3: System.out.println("Wednesday"); break;
		}
	}
}

Using the default Case

default acts as the switch equivalent of else, running only when none of the explicit case values match the switch's expression -- it's good practice to always include one to handle unexpected values gracefully.

Example: Using the default Case

java
public class Main {
	public static void main(String[] args) {
		int day = 9;
		switch (day) {
			case 1: System.out.println("Monday"); break;
			case 2: System.out.println("Tuesday"); break;
			default: System.out.println("Unknown day"); break;
		}
	}
}

Grouping Switch Cases

Stacking multiple case labels back to back with no code between them, like case 1: case 2: doSomething(); break;, makes both 1 and 2 trigger the same shared block instead of duplicating that code twice.

Example: Grouping Switch Cases

java
public class Main {
	public static void main(String[] args) {
		int num = 2;
		switch (num) {
			case 1:
			case 2:
				System.out.println("One or two");
				break;
			default:
				System.out.println("Something else");
		}
	}
}

Switch on String

Since Java 7, you can switch on a String value directly (switch (day) { case "Monday": ... }), which is often more readable than converting the string to a numeric code first just to use a switch.

Example: Switch on String

java
public class Main {
	public static void main(String[] args) {
		String day = "Monday";
		switch (day) {
			case "Monday": System.out.println("Start of week"); break;
			case "Friday": System.out.println("Almost weekend"); break;
			default: System.out.println("Midweek");
		}
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.