Java — Switch
Basic switch
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;
default:
System.out.println("Other day");
}
String switch
String fruit = "Apple";
switch (fruit) {
case "Apple":
System.out.println("Red");
break;
case "Banana":
System.out.println("Yellow");
break;
}
Switch expression (Java 14+)
String result = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
default -> "Other";
};
Mini Practice
- Write basic switch
- Use with strings
- Try switch expressions
- Practice fall-through
Up Next
Continue with While Loop - While loops.
Related Topics
Frequently Asked Questions about Switch
What is Switch in Java?
Switch is a fundamental concept in Java. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Switch?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Switch.
Why is Switch important in Java?
Switch is essential for Java development. Understanding this concept will help you write better code and solve real-world problems more effectively.