Quick revision
The short answer
javac compiles a switch on a String into two switches: the first switches on the string's hashCode() and confirms the match with equals(), which also resolves collisions, and records the index of the matching case; the second switches on that index to run the case body. An enum switch traditionally goes through a synthetic array that maps each constant's ordinal to a case number, built at run time so that reordering the enum does not break compiled code, while pattern switches since Java 21 use invokedynamic bootstraps. At the bytecode level, tableswitch is a jump table indexed directly for dense values, and lookupswitch is a sorted list of keys searched for sparse ones.
What to remember
In this answer, we saw that the JVM switches only on ints, using tableswitch for dense values and lookupswitch for sparse ones. A String switch becomes a switch on hashCode() with equals() checks that record an index, then a second switch on that index. An enum switch traditionally maps ordinals through a synthetic array built at run time, so reordering the enum is safe, while pattern switches since Java 21 use invokedynamic bootstraps. Because the generated code calls hashCode() or ordinal() first, a classic switch on null throws NullPointerException unless it declares case null.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
javac compiles a switch on a String into two switches: the first switches on the string's hashCode() and confirms the match with equals(), which also resolves collisions, and records the index of the matching case; the second switches on that index to run the case body. An enum switch traditionally goes through a synthetic array that maps each constant's ordinal to a case number, built at run time so that reordering the enum does not break compiled code, while pattern switches since Java 21 use invokedynamic bootstraps. At the bytecode level, tableswitch is a jump table indexed directly for dense values, and lookupswitch is a sorted list of keys searched for sparse ones.
Why this question is asked
Most of us never look at the bytecode of a switch, but its shape explains real behaviour: why a String switch throws NullPointerException even with a default arm, why reordering an enum in a library does not break the clients compiled against it, and why a switch over dense values is cheaper than one over scattered values. Interviewers ask this to see whether we understand how the compiler turns language features into simple JVM instructions. In this answer, we will recap the two JVM switch instructions, then follow how javac compiles a String switch, an enum switch and a pattern switch, and finish with the null behaviour that falls out of these designs.
1A Quick Recap: The JVM's Two Switch Instructions
The JVM itself only knows how to switch on an int. It has two instructions for it. tableswitch holds a low value, a high value and one jump target for every value in between, so the JVM subtracts the low value from the key, checks the range, and jumps straight to the target at that position. That is a constant-time jump, and it suits dense values like 1, 2, 3, 4.
lookupswitch holds a sorted list of key and target pairs. The JVM searches the list, which allows a binary search, so the cost grows slowly with the number of cases. It suits sparse values like 1, 1000 and 1000000, where a jump table would need a million entries. javac chooses between them with a simple cost estimate that weighs the size of the table against the number of comparisons, and we can see its choice with javap -c.
| tableswitch | lookupswitch | |
|---|---|---|
| Holds | low, high, one target per value in range | sorted key and target pairs |
| Finding the target | subtract low, index directly | search the sorted keys |
| Best for | dense values such as 1 to 10 | sparse values such as 1, 1000, 1000000 |
| Cost grows with | the width of the range (space) | the number of cases (time) |
2How a String Switch Is Compiled
Since the JVM can only switch on ints, javac turns a String switch into int switches. First it switches on s.hashCode(). Hash codes are usually scattered, so this is typically a lookupswitch. Two different strings can have the same hash code, so inside each hash case javac calls equals() against each candidate string and records the index of the case that matched. Then a second switch, on that small, dense index, runs the actual case bodies, and that one is usually a tableswitch.
Here is the idea written back as Java. "FB" and "Ea" are a well-known collision: both have the hash code 2236.
Notice the reason for the two stages. The hash narrows the candidates to one or two strings with a single int comparison, and equals() makes the result exact. The second switch exists so that fall-through and break in the original code keep their meaning: the case bodies stay in their original order in one switch.
3How an Enum Switch Is Compiled
An enum constant has an ordinal, its position in the declaration, so the obvious compilation is a switch on c.ordinal(). But ordinals are fixed when the enum is compiled, and the switch might be in a different library compiled against an older version of the enum. If someone inserts a new constant in the middle, every ordinal after it shifts, and a switch on raw ordinals would run the wrong case.
So javac traditionally generates a synthetic helper class with a static int array, often named like $SwitchMap$ followed by the enum's name. When that class is loaded, it fills the array using the ordinals of the enum as it exists at run time: map[Color.RED.ordinal()] = 1, map[Color.GREEN.ordinal()] = 2, and so on, each inside a try block that catches NoSuchFieldError in case a constant was removed. The switch itself then becomes a tableswitch on map[c.ordinal()].
Notice that the case numbers 1 and 2 belong to the switch, not to the enum. The mapping from constants to those numbers is computed when the program runs, so reordering the enum in a separately compiled library does not break the switch.
4Pattern Switches and invokedynamic
Java 21 made pattern matching for switch final, so we can switch on types, records and sealed hierarchies, with case null and guards written with when. Matching types in order cannot be expressed with a simple int switch, so javac compiles these switches differently: it emits an invokedynamic instruction whose bootstrap methods live in java.lang.runtime.SwitchBootstraps, with typeSwitch for type patterns and enumSwitch for enum constants mixed with patterns. At run time the bootstrap returns the index of the first matching case, and the code then switches on that index with an ordinary tableswitch. The exact strategy differs between javac versions, so check your version with javap -c if the details matter.
5Why a Classic Switch Throws on null
Each of these designs starts by asking the value for something: the String switch calls hashCode(), and the enum switch calls ordinal(). On a null reference both calls throw NullPointerException, before any case or default is chosen. So a classic switch on null always throws. Only a switch that declares case null, which is allowed since Java 21, routes null to an arm instead. A pattern switch without case null still throws NullPointerException, which keeps the old behaviour for existing code.
6Follow-up questions
Is a switch on Strings slower than an if-else chain of equals calls?
Usually it is faster for more than a few cases, because one hashCode call, which String caches, and one int lookup narrow the candidates to one or two equals calls, while an if-else chain may call equals on every candidate. For two or three cases the difference is negligible.
Why does the enum switch catch NoSuchFieldError?
Because the switch may run against a newer version of the enum where a constant used in a case has been removed. Catching the error leaves that slot unmapped, so the switch falls to default instead of failing when the helper class loads.
7Conclusion
In this answer, we saw that the JVM switches only on ints, using tableswitch for dense values and lookupswitch for sparse ones. A String switch becomes a switch on hashCode() with equals() checks that record an index, then a second switch on that index. An enum switch traditionally maps ordinals through a synthetic array built at run time, so reordering the enum is safe, while pattern switches since Java 21 use invokedynamic bootstraps. Because the generated code calls hashCode() or ordinal() first, a classic switch on null throws NullPointerException unless it declares case null.
Open with
The JVM only switches on ints, with two instructions. tableswitch is a jump table from a low to a high value, so it indexes directly and suits dense case values. lookupswitch is a sorted list of key and target pairs that the JVM searches, which suits sparse values. javac picks one with a cost estimate, and javap -c shows the result.
Then, if they want more
For a String switch, javac generates two switches. The first switches on hashCode, usually as a lookupswitch, and inside each hash case it calls equals against the candidate strings, which handles collisions like FB and Ea that share a hash, and stores the index of the matching case.
The second switch is on that index and runs the original bodies, so fall-through still works. For an enum, it traditionally creates a synthetic class with a SwitchMap array that maps each constant's run-time ordinal to a case number, so reordering the enum in another library does not break compiled clients.
Pattern switches from Java 21 use invokedynamic with SwitchBootstraps instead. Because these designs call hashCode or ordinal first, a classic switch on null throws NullPointerException, unless the switch has an explicit case null.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 21
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "How does the compiler implement a switch on a String, and on an enum, and how do...": https://scrivio-interview-library.netlify.app/java/operators-and-control-flow/f03c290873/