Java Switch Case Statement


Introduction

The switch statement in Java provides a way to execute one block of code out of many based on the value of an expression. It is an alternative to using multiple if-else-if statements and is especially useful when you have a single variable or expression to evaluate against several possible values.

Table of Contents

  1. What is a Switch Case Statement?
  2. Syntax of Switch Case
  3. How Switch Case Works
  4. Simple Switch Case Example
  5. Switch Case with Multiple Cases
  6. Switch Case with Default
  7. Nested Switch Case
  8. Using Strings in Switch Case
  9. Switch Case with Enum
  10. Conclusion

What is a Switch Case Statement?

A switch statement evaluates a single expression and executes a block of code that matches the value of the expression. It simplifies code by eliminating the need for multiple if-else conditions and enhances readability.

Syntax of Switch Case

Syntax:

switch (expression) {
    case value1:
        // code to be executed if expression equals value1
        break;
    case value2:
        // code to be executed if expression equals value2
        break;
    // you can have any number of case statements
    default:
        // code to be executed if expression doesn't match any case
}
  • expression: An integer, character, string, or enumeration.
  • case: A specific value that the expression is compared against.
  • break: Terminates the switch case.
  • default: Executes if no case matches the expression.

How Switch Case Works

  1. The switch statement evaluates the expression.
  2. The value of the expression is compared with the values of each case.
  3. If there is a match, the associated block of code is executed.
  4. The break statement exits the switch block.
  5. If no case matches, the default block is executed (if provided).

Simple Switch Case Example

Example:

public class SimpleSwitchCase {
    public static void main(String[] args) {
        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;
            case 4:
                System.out.println("Thursday");
                break;
            case 5:
                System.out.println("Friday");
                break;
            case 6:
                System.out.println("Saturday");
                break;
            case 7:
                System.out.println("Sunday");
                break;
            default:
                System.out.println("Invalid day");
                break;
        }
    }
}

Explanation: This program prints the name of the day based on the value of day. If day is 3, it prints "Wednesday".

Switch Case with Multiple Cases

You can group multiple cases together if they execute the same code.

Example:

public class SwitchMultipleCases {
    public static void main(String[] args) {
        int day = 5;
        switch (day) {
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
                System.out.println("Weekday");
                break;
            case 6:
            case 7:
                System.out.println("Weekend");
                break;
            default:
                System.out.println("Invalid day");
                break;
        }
    }
}

Explanation: This program groups weekdays and weekends together. If day is 5, it prints "Weekday".

Switch Case with Default

The default case is executed if no other case matches.

Example:

public class SwitchWithDefault {
    public static void main(String[] args) {
        int month = 13;
        switch (month) {
            case 1:
                System.out.println("January");
                break;
            case 2:
                System.out.println("February");
                break;
            // other cases
            default:
                System.out.println("Invalid month");
                break;
        }
    }
}

Explanation: If month is 13, it prints "Invalid month" because there is no matching case.

Nested Switch Case

You can use a switch statement inside another switch statement.

Example:

public class NestedSwitch {
    public static void main(String[] args) {
        int year = 1;
        int month = 2;
        switch (year) {
            case 1:
                switch (month) {
                    case 1:
                        System.out.println("January, Year 1");
                        break;
                    case 2:
                        System.out.println("February, Year 1");
                        break;
                    // other cases
                }
                break;
            // other cases for year
            default:
                System.out.println("Invalid year");
                break;
        }
    }
}

Explanation: This program prints the month and year based on the values of year and month.

Using Strings in Switch Case

Java 7 introduced the ability to use strings in switch statements.

Example:

public class StringSwitch {
    public static void main(String[] args) {
        String day = "Tuesday";
        switch (day) {
            case "Monday":
                System.out.println("Start of the week");
                break;
            case "Tuesday":
                System.out.println("Second day of the week");
                break;
            // other cases
            default:
                System.out.println("Invalid day");
                break;
        }
    }
}

Explanation: This program prints a message based on the value of the day string.

Switch Case with Enum

You can use enum types in switch statements to handle predefined constants.

Example:

public class EnumSwitch {
    enum Day {
        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
    }

    public static void main(String[] args) {
        Day day = Day.WEDNESDAY;
        switch (day) {
            case MONDAY:
                System.out.println("Monday");
                break;
            case TUESDAY:
                System.out.println("Tuesday");
                break;
            case WEDNESDAY:
                System.out.println("Wednesday");
                break;
            // other cases
            default:
                System.out.println("Invalid day");
                break;
        }
    }
}

Explanation: This program prints the day based on the value of the day enum.

Conclusion

The switch statement in Java is a powerful control flow statement that simplifies the code by handling multiple conditions more efficiently than using multiple if-else statements. Understanding how to use the switch statement with various data types, including integers, characters, strings, and enums, is crucial for writing clear and maintainable code.


Comments