Use string in switch case in java

java, string, switch-statement

Solution

Java (before version 7) does not support String in switch/case. But you can achieve the desired result by using an enum.

private enum Fruit {
    apple, carrot, mango, orange;
}

String value; // assume input
Fruit fruit = Fruit.valueOf(value); // surround with try/catch

switch(fruit) {
    case apple:
        method1;
        break;
    case carrot:
        method2;
        break;
    // etc...
}

Problem

I need to change the following `if`'s to a `switch`-`case` while checking for a `String`, to improve the cyclomatic complexity. ``` String value = some methodx; if ("apple".equals(value)) { method1; } if ("carrot".equals(value)) { method2; } if ("mango".equals(value)) { method3; } if ("orange".equals(value)) { method4; } ``` But I am not sure what value I'm going to get.

Original source

Related problems