Possible Duplicate:
Switch Statement with Strings in Java
I am trying to use switch statement on String but it gives compilation error. If any one suggest me how to use String in switch-case statement , it will be helpful to me.
Possible Duplicate:
Switch Statement with Strings in Java
I am trying to use switch statement on String but it gives compilation error. If any one suggest me how to use String in switch-case statement , it will be helpful to me.
There is a way if you really really want to use switch statements. Create an enum class which includes the switch statement cases
public enum MustUseSwitch{
value1,
value2,
value3;
}
and then use the enum to switch to statements.
switch(MustUseSwitch.valueOf(stringVariable)){
case value1:
System.out.println("Value1!");
break;
case value2:
System.out.println("Value2!");
break;
case value3:
System.out.println("Value3!");
break;
}
As already said, you can't. For technical details you can refer to the specification about compiling switches. With Java SE 7, this functionality has been implemented. See this page for an example using switch on String
with JDK 7.
Maybe this question could be helpful too.
You can't. Use if/else if/else if/else. Unless you are on Java7. This answer on this duplicate question can explain it far better than I can: https://stackoverflow.com/a/338230/3333
You cannot use strings directly, but you can make an array of key strings, quickly search it, and switch on the index, like this:
String[] sortedKeys = new String[] {"alpha", "bravo", "delta", "zebra"};
int keyIndex = Arrays.binarySearch(sortedKeys, switchKey);
switch(keyIndex) {
case 0: // alpha
break;
case 1: // bravo
break;
case 2: // delta
break;
case 3: // zebra
break;
}
You can't use a String
in a switch
statement but you can use the Enum
type. Using an Enum
is much better than using a String
or even a public static final int MY_CONSTANT
.
You'll find a really good tutorial here: Java Enum type tutorial