W3docs

Why can't I use switch statement on a String?

In the Java programming language, you can use a switch statement to choose between a fixed number of alternatives.

In the Java programming language, you can use a switch statement to choose between a fixed number of alternatives. The switch statement compares the value of an expression to a list of case labels, and when a match is found, the statements associated with that case are executed.

The expression used in a switch statement must be of a type that can be converted to an int value, such as byte, short, char, int, or an enum. In Java SE 7 and later, you can use a String object in the switch statement's expression. The compiler and JVM handle this natively by using hashCode() for initial dispatch and equals() for exact matching.

Here's an example of how you can use a String object in a switch statement in Java SE 7 and later:


String value = "A";

switch (value) {
    case "A":
        System.out.println("The value is A");
        break;
    case "B":
        System.out.println("The value is B");
        break;
    case "C":
        System.out.println("The value is C");
        break;
    default:
        System.out.println("The value is not A, B, or C");
        break;
}

In this example, the switch statement compares the value of the value variable to the case labels "A", "B", and "C". If a match is found, the corresponding statements are executed. If no match is found, the default case is executed.

Since Java 14, switch can also be used as an expression that returns a value, and it supports the var keyword for case labels.