Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Why can't I use switch statement on a String?

Is this functionality going to be put into a later Java version?

Can someone explain why I can't do this, as in, the technical way Java's switch statement works?
by

4 Answers

Kajalsi45d
Coming up next is a finished model dependent on JeeBee's post, utilizing java enum's as opposed to utilizing a custom strategy.
public class Main {

/

* @param args the command line arguments
*/
public static void main(String[] args) {

String current = args[0];
Days currentDay = Days.valueOf(current.toUpperCase());

switch (currentDay) {
case MONDAY:
case TUESDAY:
case WEDNESDAY:
System.out.println("boring");
break;
case THURSDAY:
System.out.println("getting better");
case FRIDAY:
case SATURDAY:
case SUNDAY:
System.out.println("much better");
break;

}
}

public enum Days {

MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
}
MounikaDasa
If you have a place in your code where you can switch on a String, then it may be better to refactor the String to be an enumeration of the possible values, which you can switch on. Of course, you limit the potential values of Strings you can have to those in the enumeration, which may or may not be desired.

Of course your enumeration could have an entry for 'other', and a fromString(String) method, then you could have

ValueEnum enumval = ValueEnum.fromString(myString);
switch (enumval) {
case MILK: lap(); break;
case WATER: sip(); break;
case BEER: quaff(); break;
case OTHER:
default: dance(); break;
}
akshay1995
Switches based on integers can be optimized to very efficent code. Switches based on other data type can only be compiled to a series of if() statements.

For that reason C & C++ only allow switches on integer types, since it was pointless with other types.

The designers of C# decided that the style was important, even if there was no advantage.

The designers of Java apparently thought like the designers of C.
RoliMishra
An example of direct String usage since 1.7 may be shown as well:

public static void main(String[] args) {

switch (args[0]) {
case "Monday":
case "Tuesday":
case "Wednesday":
System.out.println("boring");
break;
case "Thursday":
System.out.println("getting better");
case "Friday":
case "Saturday":
case "Sunday":
System.out.println("much better");
break;
}

}

Login / Signup to Answer the Question.