Java switch statement
Created By: chatGPT
Switch statements in Java provide a way to execute different parts of code based on the value of a variable or expression. It serves as a substitute for lengthy if-else-if chains and improves code clarity. Here’s how the switch statement works:
String day = "Monday";
switch (day) {
case "Monday":
System.out.println("Start of the week.");
break;
case "Tuesday":
System.out.println("Second day of the week.");
break;
case "Wednesday":
System.out.println("Midweek day.");
break;
case "Thursday":
System.out.println("Almost Friday.");
break;
case "Friday":
System.out.println("End of the week.");
break;
case "Saturday":
case "Sunday":
System.out.println("Weekend!");
break;
default:
System.out.println("Not a valid day.");
}
Key points to remember when using the switch statement: It can handle variables of types like
int
, char
, String
, and enum
. Each case represents a block of code that is executed when the value matches the case label. The break
statement is essential to prevent the execution from falling through to subsequent cases.int number = 2;
switch (number) {
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
case 3:
System.out.println("Three");
break;
default:
System.out.println("Not between 1 and 3");
}
If you omit the
break
statement, the program continues executing the next case(s) until it reaches a break or the end of the switch block. This is known as 'fall-through'. While it can be useful, it may lead to unexpected results if not handled correctly.int num = 3;
switch (num) {
case 1:
System.out.println("One");
case 2:
System.out.println("Two");
case 3:
System.out.println("Three");
break;
default:
System.out.println("No match");
}
Using multiple cases for the same block of code is possible by stacking them. This allows you to consolidate your logic where multiple cases require identical outcomes.
char grade = 'B';
switch (grade) {
case 'A':
case 'B':
System.out.println("Excellent");
break;
case 'C':
System.out.println("Well done");
break;
case 'D':
System.out.println("You passed");
break;
case 'F':
System.out.println("Better try again");
break;
default:
System.out.println("Invalid grade");
}