How to write a switch statement in java
Switches in the JVM
For more technical depth on switch. you can refer to the JVM Specification, where the compilation of switch statements is described. In a nutshell, there are two different JVM instructions that can be used for a switch, depending on the sparsity of the constants used by the cases. Both depend on using integer constants for each case to execute efficiently.
If the constants are dense, they are used as an index (after subtracting the lowest value) into a table of instruction pointers—the tableswitch instruction.
If the constants are sparse, a binary search for the correct case is performed—the lookupswitch instruction.
In de-sugaring a switch on String objects, both instructions are likely to be used. The lookupswitch is suitable for the first
switch on hash codes to find the original position of the case. The resulting ordinal is a natural fit for a tableswitch .
Both instructions require the integer constants assigned to each case to be sorted at compile time. At runtime, while the O(1) performance of tableswitch generally appears better than the O(log(n)) performance of lookupswitch. it requires some analysis to determine whether the table is dense enough to justify the space–time tradeoff. Bill Venners wrote a great article that covers this in more detail, along with an under-the-hood look at other Java flow control instructions.
Before JDK 7
Prior to JDK 7, enum could approximate a String -based switch. This uses the static valueOf method generated by the compiler on every enum type. For example:Source: stackoverflow.com