Skip to content

Switch-Case Statements

In Java, switch-case statements serve as an efficient way to have a sequence of if-else statements. It is a multi-way branch statement that provides an easy way to dispatch execution to different parts of code based on the value of an expression.

Switch-Case Statements

The switch statement evaluates an expression and attempts to match the expression's value to a case label. If a match is found, the code within that case is executed.

Here is the general syntax for a switch-case statement:

switch (expression) {
    case value1:
        // code to be executed if expression equals value1;
        break; // optional
    case value2:
        // code to be executed if expression equals value2;
        break; // optional
    ...
    default:
        // code to be executed if expression doesn't match any case values;
}

A switch-case statement can have numerous case options. The break keyword is used to exit the switch-case statement and stop the execution of more code and case testing within the block. If break is omitted, the program continues to the next case, executing the statements until a break, or the end of the switch statement is encountered.

The default keyword specifies code to run if there is no case match. The default statement must be the last case in a switch.

Let's consider an example:

int day = 3;

switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    //... we can continue this pattern for all days of the week.
    default:
        System.out.println("Invalid day");
}

In this code, the switch statement evaluates day, and when a case matches the value of day, the corresponding code block is executed. For example, if day equals 3, "Wednesday" will be printed to the terminal. If day doesn't match any case, the default statement is executed, and "Invalid day" is printed.

Tasks

For this week's tasks, we'll be practicing working with switch-case statements. In a new Java file named Week3Task2.java, complete the following tasks:

  1. Declare an integer variable named month and assign it a value of 5.
  2. Use a switch-case statement to print the name of the month corresponding to that number (1 for January, 2 for February, and so on).
  3. Add a default case to print "Invalid month" if the value of month is not between 1 and 12.
  4. Try changing the value of month and see how the output changes!

Answers

Additional Resources

W3 Schools - Switch Case Oracle Java Documentation - Switch Statement