Choosing a Path: Switch and Enhanced Switch
While if-else is great for checking ranges (like score > 90), it can become messy when you are comparing a single variable against many specific values. In Java, the Switch statement is the cleaner, more organized alternative.
1. The Traditional Switch
The classic switch statement uses the case, break, and default keywords.
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid day");
break;
}
Key Components:
break: This is critical. Without it, Java will "fall through" and execute every case below it, even if they don't match!default: This runs if none of the cases match (like the finalelsein an if-else chain).
2. The Enhanced Switch (Java 14+)
Modern Java introduced a much cleaner version of the switch. It removes the need for break statements and allows you to use the Arrow Syntax (->).
Benefits of Enhanced Switch:
- No Fall-Through: It only executes the matching block.
- Return Values: You can assign the result of a switch directly to a variable.
- Cleaner Code: No more repetitive
caseandbreaklines.
Example: Assigning a Value
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
default -> "Unknown Day";
};
System.out.println("Today is " + dayName);
3. Multiple Labels
If you want multiple cases to produce the same result, you can group them together using commas.
String type = switch (day) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> "Invalid";
};
💻 Full Practical Example: The Menu Selector
Copy this code to see the Enhanced Switch in action:
import java.util.Scanner;
public class CoffeeShop {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("--- Menu ---");
System.out.println("1. Espresso\n2. Latte\n3. Cappuccino");
System.out.print("Select your choice (1-3): ");
int choice = input.nextInt();
// Using Enhanced Switch to determine price
double price = switch (choice) {
case 1 -> 2.50;
case 2 -> 3.75;
case 3 -> 4.00;
default -> {
System.out.println("Invalid choice. Setting price to 0.");
yield 0.0; // Use 'yield' for complex logic inside a switch block
}
};
if (price > 0) {
System.out.printf("Total: $%.2f %n", price);
}
input.close();
}
}
⚠️ The yield Keyword
If you need to write more than one line of code inside an enhanced switch case, use curly braces { } and the yield keyword to return the value.
int result = switch (day) {
case 1 -> {
System.out.println("Monday");
yield 10;
}
case 2 -> {
System.out.println("Tuesday");
yield 20;
}
default -> {
System.out.println("Other day");
yield 0;
}
};
💡 Challenge: The Season Finder
Write a program that asks the user for a Month Number (1-12).
- Use an Enhanced Switch to determine the season.
- Group the months:
- 12, 1, 2 -> "Winter"
- 3, 4, 5 -> "Spring"
- 6, 7, 8 -> "Summer"
- 9, 10, 11 -> "Autumn"
- Print the result to the user.