Switch Case with string Java
Solution 1
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
Solution 2
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?
Solution 3
You can use Strings in switch statements as of Java 7.
Solution 4
As of java 7 you can use switch case with strings.. see: java switch case
Ank
Updated on June 04, 2022Comments
-
Ank almost 2 years
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?
-
Mateusz Dymczyk over 12 yearsas I said after my edit: the development of Java was really delayed because Sun was bought by Oracle.
-
fireshadow52 over 12 years@Zenzen I thought Oracle bought Java, not Sun, or are they the same thing?
-
Mateusz Dymczyk over 12 yearsNo, Oracle bought the whole company - Sun and with it Java but not only (they got also, for example, MySQL). You can find all the info here: oracle.com/us/corporate/press/018363. It took place in 2009, the talks were probably (don't remember) going on for at least months if not years and Java 6 was released in 2006 -> Java 7 didn't have the time to be properly developed by Sun.
-
Govinnage Rasika Perera about 9 yearsPersonally, I don't recommend use of switch case along with
Strings
as it is really really inefficient. At the java byte code level, JVM invokesjava.lang.String.hashCode()
for the switch case. Since same value of strings can have same hash it then compared against char by char comparison usingjava.lang.String.equals()
. -
Govinnage Rasika Perera about 9 yearscompletely agreed! ignore using switching on Strings as much as you can. Or rethink the design of your system.
-
Mateusz Dymczyk about 9 years@RasikaPerera what you're saying isn't wrong, I just don't think it would really matter in a real world application but on the other hand might make the code more readable for some people
-
Govinnage Rasika Perera about 9 years@MateuszDymczyk partially agree with you. In that case, you could use
Enums
to have maintainable, readable and performant switch statement. -
Elazar almost 7 yearsSwitching on user input is more direct than converting it to an enum (using a switch maybe?) and then switching on that enum. It also makes it easier to dependency cycles, and it is more flexible. Besides, enums were only added in Java 5, so the original decision had nothing to do with them :)