21

Why is it not possible to use enum values as strings in a switch case? (Or what is wrong with this:)

String argument;
switch (argument) {
    case MyEnum.VALUE1.toString(): // Isn't this equal to "VALUE1" ?
    // something    
break;
    case MyEnum.VALUE2.toString():
    // something else
break;
Bloke
  • 2,229
  • 3
  • 22
  • 27

3 Answers3

56

You can only use strings which are known at compile time. The compiler cannot determine the result of that expression.

Perhaps you can try

String argument = ...
switch(MyEnum.valueOf(argument)) {
   case VALUE1:

   case VALUE2:
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • The important thing is that `VALUE1` is static. You could have your own `myValueOf()` and it would still work. – Peter Lawrey Apr 30 '12 at 18:27
  • 5
    Be careful with valueOf() which throw NPE and IllegalArgumentException if argument is not valid. Bloke's code make sense to avoid to handle these exception (but sadly doesn't work). – Nereis May 28 '15 at 06:58
  • Nice solution! Thank you – Sviatlana Aug 09 '19 at 08:07
7

case MyEnum.VALUE1.toString(): // Isn't this equal to "VALUE1" ?

No, not necessarily: you are free to provide your own implementation of toString()

public enum MyType {
VALUE1 {
    public String toString() {
        return "this is my value one";
    }
},

VALUE2 {
    public String toString() {
        return "this is my value two";
    }
}

}

Moreover, someone who is maintaining your code could add this implementation after you leave the company. That is why you should not rely on String values, and stick to using numeric values (as represented by the constants MyEnum.VALUE1, MyEnum.VALUE2, etc.) of your enums instead.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • "numeric values of your enums"? Do you mean enumeration constant names of your enums? – assylias Apr 30 '12 at 16:49
  • @assylias Of course, I definitely mean using constant names, not integer literals that correspond to these names! Thanks, I edited the answer to reflect this important point. – Sergey Kalinichenko Apr 30 '12 at 16:51
1

To add to the Peter Lawrey's comments, have a look at this post from last year which discusses Switching on String in Java before and after JDK7.

Community
  • 1
  • 1
Sanjeev
  • 1,517
  • 1
  • 18
  • 30
  • Didn't even know that it wasn't possible before JDK7. Thanks, found a great link about it in a comment there: [link](http://www.xefer.com/2006/12/switchonstring) - is that the best way to process String input then? – Bloke Apr 30 '12 at 19:45
  • 1
    Well, a purist might say that you shouldn't use a switch/case statement in an OOP language at all; instead, you should go with a polymorphism strategy for dealing with something like this. IMO, if it's clear, concise, maintainable, and efficient, a case/switch is the best solution in many scenarios. – Sanjeev May 03 '12 at 17:19