- readability. a switch statement becomes A LOT more readable as the number of cases goes up compared to the equivalent if-else chain
- performance. though not as important as the previous point, switch statements can be compiled into faster code than if-else chains.
- 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.
Case Vs If-else in jdk7
-
18-06-2023 - |
سؤال
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..?
المحلول
لا تنتمي إلى StackOverflow