Switch statement with Strings in java

Switch statement with Strings in java

Yes, starting from Java SE 7, you can use the switch statement with Strings. This feature allows you to switch based on the value of a String expression. Prior to Java SE 7, only integral types like `int`, `byte`, `short`, and `char`, as well as enumerated types (`enum`), were allowed in switch statements.

Switch statement with Strings in java

Here’s an example of using a switch statement with Strings:

Example
```java
public class StringSwitchExample {
    public static void main(String[] args) {
        String day = "Monday";

        switch (day) {
            case "Monday":
                System.out.println("It's Monday!");
                break;
            case "Tuesday":
                System.out.println("It's Tuesday!");
                break;
            case "Wednesday":
                System.out.println("It's Wednesday!");
                break;
            default:
                System.out.println("It's neither Monday, Tuesday, nor Wednesday.");
        }
    }
}
```

In this example, the switch statement evaluates the `day` variable, which is a String. Based on the value of the `day` variable, it executes the corresponding case block. If none of the cases match, it executes the default block.

Using the switch statement with Strings provides a more concise and readable way to handle multiple conditions compared to nested if-else statements, especially when dealing with a large number of cases.