Domanda

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..?

È stato utile?

Soluzione

  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.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top