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.

2
  • Strings can't be used in switch statements in Java. Commented Dec 18, 2011 at 22:40
  • 4
    @Walkerneo Not true since Java7. Which is also the proposed fix: Use the newest version. Commented Dec 18, 2011 at 22:42

5 Answers 5

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Well that's obviously the same as using a hashmap from String->integer - although a neat trick.
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.

Comments

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

Comments

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;
}

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.