1

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.

Community
  • 1
  • 1
Ariel Grabijas
  • 1,472
  • 5
  • 25
  • 45

5 Answers5

5

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;
}
xarion
  • 470
  • 1
  • 4
  • 14
  • 1
    Well that's obviously the same as using a hashmap from String->integer - although a neat trick. – Voo Dec 18 '11 at 23:12
4

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.

Community
  • 1
  • 1
markusschmitz
  • 676
  • 5
  • 18
3

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

Community
  • 1
  • 1
Paul Tomblin
  • 179,021
  • 58
  • 319
  • 408
2

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;
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

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

Paul
  • 19,704
  • 14
  • 78
  • 96