Switch Statements in Java

In this tutorial we are going to learn about how to use switch statement in Java to Fir the control our program execution.


Why Switch Statement

We discussed about if else statements that are used for executing a block of code multiple times with certain conditions. But sometimes using if else statements could be too much if the conditions are more.

As a replacement of the if else statement, we use the switch statement to make our code more efficient and readable.

Recommended Books



Syntax of Switch Statement

The syntax for switch statement is:

Switch (expression): {
Case 1:
//statements of case 1
break;

Case 2:
//statements of case 2
break;

default:
//default statements

}

How Switch Statement Works

switch statement in java

The switch statements compute the expression and start comparing for the cases that are mentioned.

If a certain case is matched with expression provided within the switch statement then the code block of that certain case will be executed.

Let’s say if the expression matches case 2 then all the code present inside the case 2 block will be executed.

Break Statement

You can see that there is a break statement in every provided case. This break statement is needed to end the execution of the switch statement. If break is not mentioned after the code block of a certain case then all the cases mentioned inside the switch statement will be executed until the end.

Example:

public class months {
  public static void main(String[] args) {

    int option = 8;
    String month;

    // switch statement to check day
    switch (option) {
    case 1:
      month = "January";
      break;
    case 2:
      month = "February";
      break;
    case 3:
      month = "March";
      break;

    case 4:
      month = "April";
      break;
    case 5:
      month = "May";
      break;
    case 6:
      month = "June";
      break;
    case 7:
      month = "July";
      break;
      // our chosen month
    case 8:
      month = "August";
      break;
    case 9:
      month = "September";
      break;
    case 10:
      month = "October";
      break;
    case 11:
      month = "November";
      break;
    case 12:
      month = "December";
      break;
    default:
      month = "Invalid month";
      break;
    }
    System.out.println("Month is " + month);
  }
}

Output:

Month is August

Above, we can see that we have used the switch statement to find out the month of the year. We have created a variable known as option that is holding a certain integer value. The value is then compared to each of the month cases inside the switch statement.

Our chosen option was 8, hence statement matches case 8, and August is the month that is printed on the screen.