Switch statement

Switch Statement in Java

The switch statement in Java is a control flow statement that allows you to execute one block of code out of many based on the value of a variable or expression. It is a more readable alternative to a series of if-else if-else statements when you need to compare a variable to multiple potential values.


1. What is a switch Statement?

A switch statement evaluates a single expression and then matches its value against a list of possible cases. Each case has its own block of code that will be executed if the expression matches that case. If none of the cases match, an optional default case can be executed.

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;
    // More cases...
    default:
        // Code to be executed if no cases match
}
  • expression: This is the value being tested, such as a variable or a result of a calculation.

  • case: Each case keyword represents a potential value for the expression. If the expression matches a case, the code following that case will be executed.

  • break: The break statement exits the switch block. Without break, the program will continue to execute the following cases, which is called "fall-through."

  • default: This optional case is executed if none of the other cases match the expression.


2. Example of a Basic switch Statement

Here's a simple example of using a switch statement to determine the day of the week based on a number:

int day = 3;
String dayName;

switch (day) {
    case 1:
        dayName = "Monday";
        break;
    case 2:
        dayName = "Tuesday";
        break;
    case 3:
        dayName = "Wednesday";
        break;
    case 4:
        dayName = "Thursday";
        break;
    case 5:
        dayName = "Friday";
        break;
    case 6:
        dayName = "Saturday";
        break;
    case 7:
        dayName = "Sunday";
        break;
    default:
        dayName = "Invalid day";
}

System.out.println("Day of the week: " + dayName);

In this example, the value of day is compared against the cases. Since day is 3, the output will be "Day of the week: Wednesday."


3. Using the default Case

The default case is executed if none of the other cases match the expression. It acts as a fallback option.

Example:

int month = 13;
String monthName;

switch (month) {
    case 1:
        monthName = "January";
        break;
    case 2:
        monthName = "February";
        break;
    // Other cases...
    default:
        monthName = "Invalid month";
}

System.out.println("Month: " + monthName);

In this example, since the value of month is 13, which doesn't match any case, the default case will be executed, resulting in "Month: Invalid month."


4. switch Statement with Multiple Cases

In some situations, multiple cases may execute the same block of code. You can group these cases together without repeating the code.

Example:

char grade = 'B';

switch (grade) {
    case 'A':
    case 'B':
    case 'C':
        System.out.println("Pass");
        break;
    case 'D':
    case 'F':
        System.out.println("Fail");
        break;
    default:
        System.out.println("Invalid grade");
}

In this example, if the grade is 'A', 'B', or 'C', the program prints "Pass." If the grade is 'D' or 'F', it prints "Fail."


5. switch Statement with Strings

Starting from Java 7, the switch statement also supports strings. This allows you to use switch with string values.

Example:

String fruit = "Apple";

switch (fruit) {
    case "Apple":
        System.out.println("You chose Apple");
        break;
    case "Banana":
        System.out.println("You chose Banana");
        break;
    case "Cherry":
        System.out.println("You chose Cherry");
        break;
    default:
        System.out.println("Unknown fruit");
}

In this example, the string "Apple" matches the first case, so the output will be "You chose Apple."


6. Nested switch Statements

You can nest one switch statement inside another. This is useful when you need to perform multiple levels of checks.

Example:

int category = 1;
int item = 2;

switch (category) {
    case 1:
        switch (item) {
            case 1:
                System.out.println("Category 1, Item 1");
                break;
            case 2:
                System.out.println("Category 1, Item 2");
                break;
        }
        break;
    case 2:
        System.out.println("Category 2");
        break;
    default:
        System.out.println("Unknown category");
}

In this example, the outer switch checks the category, and the inner switch checks the item. Since category is 1 and item is 2, the output will be "Category 1, Item 2."


7. Fall-Through Behavior

In Java, if you omit the break statement in a case, the program will "fall through" and execute the next case, even if the next case's condition isn't met. This is useful in some situations, but it can lead to bugs if used unintentionally.

Example:

int number = 2;

switch (number) {
    case 1:
        System.out.println("One");
    case 2:
        System.out.println("Two");
    case 3:
        System.out.println("Three");
    default:
        System.out.println("Default");
}

In this example, the output will be:

Two
Three
Default

This happens because there are no break statements, so the program falls through to the next cases.


Conclusion

The switch statement is a powerful tool for managing multiple conditions in your Java programs. It provides a more organized and readable alternative to a series of if-else statements, especially when dealing with many possible values. Understanding how to use the switch statement, along with its case, break, and default components, will help you write cleaner and more efficient code.

For more Java tutorials and resources, visit codeswithpankaj.com.

Last updated