This is probably old news to most of you java devs but in case you
didn’t know, as of Java 7 you can use the switch-case
construct
on a String
as well. Evidently, it is more optimized than a
regular if-then.
… The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.
That means that now (haha I said, “now”) you can use:
String something = "whatever";
switch(something) {
case "whatever":
doSomeJunk();
break;
case "somethingElse":
whatever();
break;
// ...
}
And it will actually out perform a standard if-then:
String something = "whatever";
if (something.equals("whatever")) {
doSomeJunk();
}
else if (something.equals("somethingElse")) {
whatever();
}
else if ( /* ... */ ) {
// ...
}
else if ( /* ... */ ) {
// ...
}
// ... and so on
Ain’t that great for our hands? Less typing!
Strings in switch statements from the Java 7 documentation provides us with a more practical example:
public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
String typeOfDay;
switch (dayOfWeekArg) {
case "Monday":
typeOfDay = "Start of work week";
break;
case "Tuesday":
case "Wednesday":
case "Thursday":
typeOfDay = "Midweek";
break;
case "Friday":
typeOfDay = "End of work week";
break;
case "Saturday":
case "Sunday":
typeOfDay = "Weekend";
break;
default:
throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
}
return typeOfDay;
}