Java - Switch Case

In Java, the switch case statement is used to control the flow of execution based on a certain condition. It is a multi-branching statement, just like an if-else statement, but provides a more concise way to write the code when there are multiple options to choose from.

The syntax of the switch case statement is as follows:

switch(expression) {
  case value1:
    // code block
    break;
  case value2:
    // code block
    break;
  case value3:
    // code block
    break;
  ...
  default:
    // code block
}

Here's what each component of the switch case statement does:

  • The switch keyword is followed by an expression inside parentheses that is evaluated once.
  • The case keyword is followed by a value that the expression might match. If the expression matches a value, the code inside that case statement will be executed.
  • The break keyword is used to break out of the switch case statement. If it is not used, then the code execution will continue to the next case statement, regardless of whether the expression matches the value of the case.
  • The default keyword is used when none of the cases match the expression value. It is like an else statement in an if-else statement.

Now let's take a look at an example of how to use the switch case 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;
  case 6:
    dayName = "Saturday";
    break;
  case 7:
    dayName = "Sunday";
    break;
  default:
    dayName = "Invalid day";
    break;
}
System.out.println("The day is " + dayName);

In this example, we declare a variable day and set it to 3. We then use a switch case statement to check the value of day. Since the value of day matches the value of case 3, the code inside that case statement is executed, which sets the dayName variable to "Wednesday". The output of this program is "The day is Wednesday".