Core Java Fundamentals ยท Conditional Statements

Switch Statement

Learn how to use the switch statement to control the flow of execution based on the value of a variable or expression.

SwitchDemo.java

public class SwitchDemo {
    public static void main(String[] args) {
        int day = 4; // Let's check the 4th day of the week
        String dayString;

        switch (day) {
            case 1:
                dayString = "Monday";
                break;
            case 2:
                dayString = "Tuesday";
                break;
            case 3:
                dayString = "Wednesday";
                break;
            case 4:
                dayString = "Thursday";
                break;
            case 5:
                dayString = "Friday";
                break;
            case 6:
                dayString = "Saturday";
                break;
            case 7:
                dayString = "Sunday";
                break;
            default:
                dayString = "Invalid day";
                break;
        }
        System.out.println("The day is: " + dayString);
    }
}

Step by step

  1. The main method begins. We declare an integer variable day and initialize it with the value 4.
  2. Next, we declare a String variable dayString. It is not yet initialized, so it holds a null value.
  3. The program encounters a switch statement. It evaluates the expression inside the parentheses, which is the variable day. The value is 4.
  4. The switch block looks for a case label that matches the value 4. It skips cases 1, 2, and 3 and finds a match at case 4.
  5. The code inside case 4 is executed. The string "Thursday" is assigned to the dayString variable.
  6. The break statement is executed. This immediately terminates the switch block, and the program continues execution after the switch.
  7. The program is now outside the switch block. This line prints the final value of dayString to the console.