Skip to main content

Control Flow

Switch statement

In our previous lessons, we learned about the if...else statement, which helps us make decisions between two options. But what if we have to choose from more than two options?

For instance, let's say we're given a number from 1 to 7, and we need to print the corresponding day of the week. If the number is 1, it's Sunday; if it's 2, it's Monday, and so on.

While we could use a series of if...else if statements for each number, this can get messy and be hard to follow.

Enter the switch statement – a better way to handle such situations.

Now, let's dive into the syntax of the switch statement.

Syntax

switch (dayNumber) {
    case 1:
        // Do something for Sunday
        break;

    case 2:
        // Do something for Monday
        break;

    // ... cases for other days ...
    default:
        // If none of the above cases match, do something here
}

In simpler terms:

  • You have a number (like 1, 2, 3...) that represents a day.
  • The switch statement checks the value of that number.
  • If it matches one of the cases (like case 1 for Sunday), it does something specific for that case.
  • If it doesn't match any case, it goes to the default case and does something there.

Think of it like a decision tree for different days. Much neater, right? Oh, and we use the "break" to tell the program to stop checking cases once it finds the right one.

Now, let's solve the same problem we just discussed with a switch statement.

Don't worry, the program might look long, but it's actually easier to understand than the one we wrote in our previous lessons.

import java.util.Scanner;

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

        // Take a number input
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a number between 1 to 7: ");
        int number = input.nextInt();

        // Corresponding case is executed depending on the value of number
        switch (number) {
            case 1:
                System.out.println("It's Sunday!");
                break;

            case 2:
                System.out.println("It's Monday!");
                break;

            case 3:
                System.out.println("It's Tuesday!");
                break;

            case 4:
                System.out.println("It's Wednesday!");
                break;

            case 5:
                System.out.println("It's Thursday!");
                break;

            case 6:
                System.out.println("It's Friday!");
                break;

            case 7:
                System.out.println("It's Saturday!");
                break;

            default:
                System.out.println("Invalid Number");
        }
    }
}

Sample Input

Enter a number between 1 to 7: 
6

Output

It's Friday!
Explanation
The user has entered the number 6.

The switch statement checks the value of number.

Since number is 6, it matches the case labeled 6: (i.e., case 6:).

The program then executes the code inside this case, which is System.out.println("It's Friday!");
This line of code prints the message "It's Friday!" to the console.

After the code inside the case is executed, the break; statement is encountered. The break; statement is used to exit the switch statement and continue with the rest of the program outside the switch.

So, when the user enters 6, the program recognizes that it corresponds to Friday and prints the message accordingly.

What will happen if we don't use break statement inside case?

If you don't use the break statement after each case in a switch statement, the program will continue executing the code for subsequent cases, regardless of whether their conditions are met. This behaviour is known as "fall-through."

import java.util.Scanner;

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

        // Take a number input
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a number between 1 to 7: ");
        int number = input.nextInt();

        // Corresponding case is executed depending on the value of number
        switch (number) {
            case 1:
                System.out.println("It's Sunday!");
                // No break here

            case 2:
                System.out.println("It's Monday!");
                // No break here

            case 3:
                System.out.println("It's Tuesday!");
                // No break here

            case 4:
                System.out.println("It's Wednesday!");
                // No break here

            case 5:
                System.out.println("It's Thursday!");
                // No break here

            case 6:
                System.out.println("It's Friday!");
                // No break here

            case 7:
                System.out.println("It's Saturday!");
                // No break here

            default:
                System.out.println("Invalid Number");
        }
    }
}

Now, if the user enters 6, the output will be:

It's Friday!
It's Saturday!
Invalid Number

Because there are no break statements after each case, the program "falls through" to the subsequent cases, executing their code as well. This is usually not the desired behavior, and it can lead to unexpected results. Using break is crucial to ensure that only the code corresponding to the matched case is executed.