Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use string in switch case in java

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.

like image 663
randeepsp Avatar asked Apr 20 '12 05:04

randeepsp


People also ask

Can I use String in switch case in Java?

Yes, we can use a switch statement with Strings in Java.

Can Strings be used in switch?

String is the only non-integer type which can be used in switch statement.

How do you match a String in a switch case?

To ensure that we have a match in a case clause, we will test the original str value (that is provided to the switch statement) against the input property of a successful match . input is a static property of regular expressions that contains the original input string. When match fails it returns null .

Can we use object in switch case in Java?

We can use Byte, Integer, Short and Long variables with wrapper classes in switch statements in Java. Explanation: In the above code snippet, Integer is an object as it is converted from primitive data type (int) to object (Integer).


1 Answers

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... } 
like image 163
nickdos Avatar answered Oct 21 '22 01:10

nickdos