In Java 7 a string object can be in the expression of a switch statement. Can someone explain the below statement from official documentation?
The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.
Java Code
Having two versions of a class, e.g.
With
if-then-else:With
switch:Bytecode
Let’s take a look at the bytecode. Getting the bytecode for
if-then-elseversion:Getting the bytecode for
switchversion:Conclusion
In the first version compares the string by calling the
equalsmethod for each condition, until it is found.In the second version is obtained first
hashCodeof the string. Then this is compared with the values hashCodeeachcase. See thelookupswitch. If any of these values is repeated just happens to run the code for thecase. Otherwise, call theequalsmethod of the cases tied. This is much faster than ever call theequalsmethod only.