What javac does
Switch on a String
A switch on hashCode(), equals() to confirm, then a second switch.
A switch on a String (Java 7) compiles into two switches. The first is a lookupswitch on s.hashCode(); each of its cases calls equals to rule out a hash collision and sets a hidden index. The second is a tableswitch on that index, which jumps to your code.
The source
// A switch on a String: a switch on hashCode() first, then equals(), then a second switch.
public class StringSwitch {
static int days(String month) {
switch (month) {
case "feb":
return 28;
case "apr":
case "jun":
case "sep":
case "nov":
return 30;
default:
return 31;
}
}
}Compiled by javac 25 with -g and --release 8 to 25. Where releases produce different bytecode, each version is shown.
What to look for
- The hash codes are computed by javac: 101251 is
"feb".hashCode(). - javac copies the string into a hidden local and starts the index at -1 (
iconst_m1); a string that matches nothing keeps -1 and lands on the default. - Cases that share a body share a target: indexes 1 to 4 all jump to
return 30. - Because the first thing it does is call
hashCode(), switching on a null String throws NullPointerException.
StringSwitch.class
static int days(String month)
javac --release 8 to 25 (the same bytecode for every release)