1

In jdk7, case statements accept Strings. I have a scenario where i have to check if a String is present in list of strings and then perform operation.

Case "Car":
      syso("nice car");
      break;
case "bike":
      syso("nice bike");
      break;
default:
      syso("buy something");

or

if(stringList.contains("Car")){
syso("nice car");
}else if(stringList.contains("bike")){
syso{"nice bike");
}else{
syso{"buy something");
}

Till jdk6 case statements did not support Strings. What can be main advantages of this new feature however the same thing can be implemented using if-else..?

Mithun Khatri
  • 636
  • 3
  • 9
  • 22
  • Hmm, given what you want to do, I don't see how a switch statement helps here – fge Mar 20 '14 at 18:19
  • Another SO question in regards to the `switch` statement with `String` .. old, but the answer is relevant: http://stackoverflow.com/questions/338206/switch-statement-with-strings-in-java – txtechhelp Mar 20 '14 at 18:22

1 Answers1

7
  1. readability. a switch statement becomes A LOT more readable as the number of cases goes up compared to the equivalent if-else chain
  2. performance. though not as important as the previous point, switch statements can be compiled into faster code than if-else chains.
  3. fall-through. a lot less important than the previous two, and rare enough to be flagged as a warning by some IDE's/tools, there are still cases where you can benefit from a fall-through (==no break after a particular case). this ties into readability again.
radai
  • 23,949
  • 10
  • 71
  • 115
  • +1 for readability. I care less about the minute performance gain. – Isaiah van der Elst Mar 20 '14 at 18:19
  • 1
    I have a doubt in your 2nd point. Performance depends on if its used in any loop or not. I think if-else gives better performance if run in loop. – Mithun Khatri Mar 20 '14 at 18:25
  • @MithunKhatri - if you read up on it here (http://stackoverflow.com/questions/338206/switch-statement-with-strings-in-java) you'll see that switching on strings is basically composed of 2 steps - "hash-code"ing the string and then switching by hashcode (im simplifying). this means that it scales much better than a long chain of if-elses (jump table instead of a long sequence of compare-and-jump ops) – radai Mar 20 '14 at 18:31
  • @radai until Java 7 (not sure in Java 8) switch does not use a jump table for small amounts of cases (< 18). Your other points still stand. – assylias Mar 20 '14 at 18:33
  • @assylias - i know. thats why i said "scales much better". for a small set of options it might very well be slower – radai Mar 20 '14 at 18:34