This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Hmm...what is the mechanics behind the switch case with string, does it do it by comparing the string values?
It will be good to have the Object version comparison too...maybe in a future Java release?
Similar to how the Object with proper overidden equals() and hascode() can be used as a key for Map.
Can we use String expressions in the switch case, an expression which returns a string value at run-time?
Joined: Mar 05, 2008
I'm not sure of the exact mechanics, but it must compare values at some point, yes. One could analyze the bytecode to find out exactly; I don't have time at the moment.
It's certainly possible to imagine a version of switch that would allow arbitrary objects and use equals(). That's available in other languages. Java's switch tends to be designed for cases that it can execute very quickly. For anything else, it's possible to just use a series of if /else if / else statements.
For case values, you can only use constant expressions which can be fully evaluated at compile time. The argument to the switch can be an unknown variable, but the cases need to be exactly known by the compiler.