Java Switch in Java
In Java, the switch statement is used to execute one of many code blocks based on the value of a given expression. It's an alternative to using multiple if-else statements when you need to check a variable against several different values.
Syntax of switch Statement:
switch (expression) { case value1: // code block to be executed if expression == value1 break; case value2: // code block to be executed if expression == value2 break; case value3: // code block to be executed if expression == value3 break; // You can have any number of case statements. default: // code block to be executed if expression doesn't match any value}Explanation:
expression: The value or expression you want to check.case valueX:: Eachcaserepresents a possible value for the expression.break;: Thebreakstatement is used to terminate theswitchstatement once a match is found and the corresponding code block is executed. Withoutbreak, the program will "fall through" and execute the code for the subsequent cases.default:: This is optional. It defines a block of code that gets executed if nocasematches the value of the expression.
Example: Basic switch Statement
Here’s an example using a switch statement to check for different days of the week:
public class SwitchExample { public static void main(String[] args) { int day = 3; // Let's assume 1 = Monday, 2 = Tuesday, 3 = Wednesday, etc. switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; case 4: System.out.println("Thursday"); break; case 5: System.out.println("Friday"); break; case 6: System.out.println("Saturday"); break; case 7: System.out.println("Sunday"); break; default: System.out.println("Invalid day"); } }}Output:
WednesdayImportant Notes:
The
breakStatement:
Thebreakis crucial because without it, the program would continue executing the followingcasestatements even if one of the cases matched, a behavior known as "fall through."defaultCase:The
defaultcase is executed if none of thecaselabels match theexpression. It’s optional, but it’s good practice to include it to handle unexpected values.
Data Types for
switchExpression:
Theexpressionin aswitchstatement can be one of the following data types:byte,short,int,charString(since Java 7)enum(since Java 5)
Example: switch with Strings
Here’s an example of using a switch statement with String values:
public class SwitchStringExample { public static void main(String[] args) { String day = "Wednesday"; switch (day) { case "Monday": System.out.println("Start of the week!"); break; case "Wednesday": System.out.println("Midweek day"); break; case "Friday": System.out.println("End of the workweek"); break; default: System.out.println("Invalid day"); } }}Output:
Midweek dayExample: switch with enum
You can also use switch with enum values. Here’s an example:
public class SwitchEnumExample { enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } public static void main(String[] args) { Day day = Day.WEDNESDAY; switch (day) { case MONDAY: System.out.println("Start of the week!"); break; case WEDNESDAY: System.out.println("Midweek day"); break; case FRIDAY: System.out.println("End of the workweek"); break; default: System.out.println("Weekend!"); } }}Output:
Midweek dayExample: switch Without break (Fall-Through Behavior)
If you omit the break statement, the program will fall through and execute all subsequent case blocks, even if a match is found.
public class SwitchFallThroughExample { public static void main(String[] args) { int day = 3; switch (day) { case 1: System.out.println("Monday"); case 2: System.out.println("Tuesday"); case 3: System.out.println("Wednesday"); case 4: System.out.println("Thursday"); default: System.out.println("Invalid day"); } }}Output:
WednesdayThursdayInvalid dayJava 12 switch Expression (Enhanced switch)
In Java 12, a new version of the switch statement was introduced, where you can return a value directly from each case.
public class SwitchExpressionExample { public static void main(String[] args) { int day = 3; String dayName = switch (day) { case 1 -> "Monday"; case 2 -> "Tuesday"; case 3 -> "Wednesday"; case 4 -> "Thursday"; case 5 -> "Friday"; case 6 -> "Saturday"; case 7 -> "Sunday"; default -> "Invalid day"; }; System.out.println(dayName); }}Output:
WednesdayKey Takeaways:
switchis used when you need to check a variable against multiple possible values.It works with
int,char,String, andenumtypes.The
breakstatement is necessary to stop the execution of furthercaseblocks.Fall-through can be achieved by omitting the
breakstatement.Java 12 introduced the enhanced
switchexpression, allowing for more concise syntax and direct value returns.
Let me know if you need more details or examples!