Java switch statement

The switch statement is a multi-way branch statement. It provides a simple way to dispatch execution to different parts of the code based on the value of the expression. Basically, expressions can be byte, short, char, and int primitive data types. Starting from JDK7, it also applies to enumerated types (Enums in Java), String classes, and Wrapper classes.

In Java, the switch statement is a control statement that allows you to execute different actions based on different values of a variable or expression. The syntax of the switch statement is as follows: 

 

switch (expression) {
   case value1:
      // code block to be executed if expression matches value1
      break;
   case value2:
      // code block to be executed if expression matches value2
      break;
   case value3:
      // code block to be executed if expression matches value3
      break;
   ...
   default:
      // code block to be executed if expression does not match any case
      break;
}

The switch statement evaluates the expression and then compares it with the values in each case statement. If a match is found, the code block associated with that case statement is executed. The break statement is used to exit the switch block once a matching case has been found. If none of the cases match, the code block associated with the default statement is executed.

Here's an example of a switch statement in Java: 

 

int day = 3;
String dayName;
switch (day) {
   case 1:
      dayName = "Monday";
      break;
   case 2:
      dayName = "Tuesday";
      break;
   case 3:
      dayName = "Wednesday";
      break;
   case 4:
      dayName = "Thursday";
      break;
   case 5:
      dayName = "Friday";
      break;
   default:
      dayName = "Invalid day";
      break;
}
System.out.println("The day is " + dayName);

In this example, the value of the day variable is compared with each case statement. Since day is equal to 3, the code block associated with the case 3 statement is executed and the dayName variable is set to "Wednesday". Finally, the value of dayName is printed to the console.

 

Submit Your Programming Assignment Details