I used java after a long time and found out that unlike other languages java doesn't support switch case with strings(only with no's and enums). What's the reason behind it? If other languages implement it easily, why not java?
-
possible duplicate of Switch Statement with Strings in JavaWayne– Wayne2012-01-12 20:53:13 +00:00Commented Jan 12, 2012 at 20:53
-
Thanks for the link.. I googled searched this before asking this question.. but didn't find that link in my search..Ank– Ank2012-01-12 20:55:13 +00:00Commented Jan 12, 2012 at 20:55
-
What language allows strings in switch statements?Hot Licks– Hot Licks2012-01-12 20:56:13 +00:00Commented Jan 12, 2012 at 20:56
-
1@Ankur I very much doubt that C supports switching on strings, characters yes (so does Java).Ben van Gompel– Ben van Gompel2012-01-12 21:26:05 +00:00Commented Jan 12, 2012 at 21:26
-
@Ankur How do you do it in C?Fredrik– Fredrik2012-01-12 21:28:17 +00:00Commented Jan 12, 2012 at 21:28
6 Answers
This feature was implemented in Java 7 (which was released in July this year). Why didn't they implement it earlier? Well J7 was really delayed because of the whole Sun acquisition by Oracle.
Latest documentation: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
6 Comments
Strings as it is really really inefficient. At the java byte code level, JVM invokes java.lang.String.hashCode() for the switch case. Since same value of strings can have same hash it then compared against char by char comparison using java.lang.String.equals().IMO, the designers of Java were smart to leave out switching on Strings. Everytime you do a switch on a String (and, I admit, I do it sometimes too) you should be thinking:
- Why aren't I using polymorphism here?
- At the very least, should I be using an Enum instead?
2 Comments
The new Java Version (JDK 7) takes long time to release. That's why you may not be able to know that.... Here is an example how to use strings in switch case...
option = scanner.nextLine();
switch (option) {
case "1": System.out.println("Hello");break;
case "2": break;
case "3": break;
case "4": break;
case "5": break;
default: System.out.println("Invalid option. Please try again..."); break;
}
Comments
Not very pretty but here is another way for Java 6 and bellow:
String runFct =
queryType.equals("eq") ? "method1":
queryType.equals("L_L")? "method2":
queryType.equals("L_R")? "method3":
queryType.equals("L_LR")? "method4":
"method5";
Method m = this.getClass().getMethod(runFct);
m.invoke(queryField);