Switch statement!

I want to know if there is an equivalent statement to the switch-case statement for the strings
[109 byte] By [hhad] at [2007-9-26 2:18:53]
# 1
Hi, Switch, if, if-else are the selection statements in java. You can acheive the same with the help of if and if-else in java.I hope this will help you.ThanksBakrudeen
bakrudeen_indts at 2007-6-29 9:20:28 > top of Java-index,Archived Forums,Java Programming...
# 2
u can always replace a switch case with an if else construct. and if else works with strings as well
parul_patidar at 2007-6-29 9:20:28 > top of Java-index,Archived Forums,Java Programming...
# 3

You can use switch with strings, however you need to test it carefully. Here's how; since String is of type Object it supports the hashCode() function. This will return a 'nearly' unique integer for any given string, and two different but identical strings will produce the same hash code.

Here's the tricky part; you need to remember that the hash code, while good, may return the same code for two different strings! This is why you must test. If however, all the strings to be compared are known at compile time, and you make sure that the hash for each one is different (which is most likely) you will have no problem. Hope this works for you, good luck.

cajo at 2007-6-29 9:20:28 > top of Java-index,Archived Forums,Java Programming...
# 4

There's a worse problem for using the hashCode of Strings to allow you to use Strings in a switch: the hashCode of a given String can vary from JVM to JVM, and even between versions of JVMs! Because the values in the case labels must be compile-time constants, you cannot use switch and Strings portably.

schapel at 2007-6-29 9:20:28 > top of Java-index,Archived Forums,Java Programming...
# 5
These are excellent points! You need to carefully consider if your really need to use Strings in a switch statement. To do this, you are trying to end-run the language. While it is possible, it will not be convienient.
cajo at 2007-6-29 9:20:28 > top of Java-index,Archived Forums,Java Programming...