Video in progress

Strong Middle ⚙️ JVM and memory

How does a switch on a String work in bytecode, and when are tableswitch and lookupswitch chosen?

static int price(String plan) {
    switch (plan) {
        case "basic": return 10;
        case "pro":   return 25;
        case "team":  return 60;
        default:      return 0;
    }
}

javac turns a String switch into two steps: first a lookupswitch on hashCode(), then an exact check with equals() and a second switch on an internal index. tableswitch is a single jump through an index for dense values, while lookupswitch is a search in a sorted table for sparse values.

📖 Answer

The JVM has switch instructions only for int. javac turns this code into roughly this:

int idx = -1;
switch (plan.hashCode()) {              // lookupswitch: the hashes are sparse
    case 93508654: if (plan.equals("basic")) idx = 0; break;
    case 111277:   if (plan.equals("pro"))   idx = 1; break;
    case 3555933:  if (plan.equals("team"))  idx = 2; break;
}
switch (idx) {                          // tableswitch: 0,1,2 are dense
    case 0: return 10;
    case 1: return 25;
    case 2: return 60;
    default: return 0;
}

A few practical things follow from this:

  • if plan is null, you get an NPE in hashCode(). In Java 21 pattern matching switch you can write case null.
  • If two strings have the same hash, there are several equals checks inside one case, and it still works correctly.
  • String.hashCode() is cached in the string, so a repeated switch is cheap.

tableswitch vs lookupswitch: javac works out how dense the case values are. 1, 2, 3, 4 get a table, an O(1) jump. 1, 1000, 50000 get sorted pairs and a binary search. Then the JIT optimizes both in its own way (often an if chain or a jump table), so this difference is usually not a performance question.

For an enum switch, javac used to use a synthetic $SwitchMap$... array; newer javac versions and pattern matching switch are moving to invokedynamic (SwitchBootstraps). Check it yourself with javap -c -p, as it differs by JDK version.