How does a switch statement on Strings work internally?

Since Java 7 you can switch on a String. The compiler translates it into two steps: first a switch on the String's hashCode(), then an equals() check to confirm the match (because different strings can share a hash code), and finally a switch on an index to run the right case.

Key Points: • The selector is compared with equals(), so the match is case-sensitive. • A null selector throws NullPointerException, because hashCode() is called on it. Java 21 pattern switches can handle case null explicitly. • Performance is close to an if-else chain of equals() for a few cases, and better for many cases thanks to the hash-based jump. • Case labels must be compile-time constants. • Switch expressions (Java 14) with arrow labels work the same way with Strings.

Code Example:

public class StringSwitch {

    static int discount(String tier) {
        return switch (tier) {
            case "GOLD" -> 20;
            case "SILVER" -> 10;
            case "Aa", "BB" -> 1;        // "Aa" and "BB" have the same hashCode
            default -> 0;
        };
    }

    public static void main(String[] args) {
        System.out.println("GOLD: " + discount("GOLD"));
        System.out.println("gold: " + discount("gold"));
        System.out.println("hashCodes: " + "Aa".hashCode() + " and " + "BB".hashCode());
        System.out.println("BB: " + discount("BB"));

        try {
            discount(null);
        } catch (NullPointerException e) {
            System.out.println("null selector: NullPointerException");
        }
    }
}

Output:

GOLD: 20 gold: 0 hashCodes: 2112 and 2112 BB: 1 null selector: NullPointerException

Good to Know: Roughly what the compiler generates: switch (tier.hashCode()) { case 2193504: if (tier.equals("GOLD")) index = 0; break; … } followed by switch (index) { case 0: return 20; … }. You can see it yourself by compiling a class and running javap -c on it.

Interview Tip: A concise interview answer is:

"The compiler turns a String switch into a switch on hashCode(), then confirms the match with equals() because different strings can share a hash, and then jumps to the right case. So it's case-sensitive, it throws NullPointerException for a null selector, and it's efficient even with many cases."

Previous question: Why is a char[] preferred over a String for storing passwords?

Next question: What are Compact Strings in Java 9?

More Java Strings interview questions

All Java Strings questions