Java switch Statement
In Java, the switch statement allows you to create a decision structure that tests a single variable against multiple values. It provides a more concise and structured way to write multiple if-else statements for the same variable.
Here is the basic syntax of the switch statement in Java:
switch (variable) { case value1: // code to execute if variable is equal to value1 break; case value2: // code to execute if variable is equal to value2 break; ... default: // code to execute if variable does not match any of the case values break; }
The switch statement evaluates the value of the variable and compares it against each of the case values. If a match is found, the corresponding code block is executed. The break
statement is used to exit the switch statement after the corresponding code block has been executed.
If none of the case values match the value of the variable, the code in the default block is executed. The default block is optional.
Here is an example that uses the switch statement to check the value of a variable and print a message based on its value:
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; case 4: System.out.println("Thursday"); break; case 5: System.out.println("Friday"); break; default: System.out.println("Invalid day"); break; }
In this example, the program checks the value of the variable day
and prints a message based on its value. If day
is 3, the output will be "Wednesday". If day
is 7 or any other value that is not covered by the cases, the output will be "Invalid day" because of the default block.