Tuesday, August 30, 2011
How to use string in switch case in Jdk 7 with example
Have you ever feel that String should be used in switch cases as like int and char? JDK 7 has made an important enhancement in there support of String, now you can use String in switch and case statement, No doubt String is most widely used type in Java and in my opinion they should have made this enhancement long back when they provided support for enum in java and allowed enum to be used in switch statement. In this java tutorial we will see how we can use String inside switch and case statement in JDK 7. This article is in continuation of my earlier post on JDK7 feature improved exception handling using multi cache block in Java
many a times we want to switch based upon string output received from user or other part of program but before JDK7 we can't do it directly instead either we need to map those String to final integer constant or char constant to use them inside switch and case or you need to fallback on if-else statement which gets clumsy once number of cases getting increased. But now with jdk7 you can directly use String
inside switch and case statement. Though it’s pretty straight forward feature let see an example of how to use String inside switch and case statement in JDK7.
Example of String in Switch prior JDK7
> else <
throw new IllegalArgumentException();
Overall allowing String into switch and case statement is not a wow feature but in my opinion very useful one and definitely makes coding easier and make code more readable by either removing clumsy if-else statement. So I definitely vote plus one to JDK 7 String in switch feature and thanks to guys involved in project coin for making life easier of java developers.
You also need to ensure that your JRE must have source 1.7 otherwise if you try to run string in switch in JRE less than 7 you will get following errro
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - strings in switch are not supported in -source 1.6
(use -source 7 or higher to enable strings in switch)
That’s all from me on String and Switch on JDK7, Please share how you are using this new feature of java 7.
Here are some of my other post on Java you may find interesting: