Sunday, August 8, 2021

How to use String in switch case in Java with Example

Have you ever feel that String should be used in switch cases like int and char? JDK 7 has made an important enhancement in their support of String, now you can use String in switch and case statements, No doubt String is the 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 a 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


string and switch in jdk7 example tutorial many times we want to switch based upon string output received from a user or another part of the program but before JDK7 we can't do it directly instead either we need to map those String to a final integer constant or char constant to use them inside switch and case or you need to fall back on the if-else statement which gets clumsy once the number of cases getting increased. 

But now with jdk7, you can directly use String inside switch and case statement. Though it’s a pretty straightforward feature let see an example of how to use String inside switch and case statement in JDK7.


Example of String in Switch in JDK7


public static void tradingOptionChooser(String trading) {
 switch (trading) {
  case "Stock Trading":
       System.out.println("Trader has selected Stock Trading option");
       break;
  case "Electronic Trading":
       System.out.println("Trader has selected Electronic Trading option");
       break;
  case "Algorithmic Trading":
       System.out.println("Trader has selected Algorithmic Trading option");
       break;
  case "Foreign exchange trading":
       System.out.println("Trader has selected Foreign exchange Trading option");
       break;
  case "commodity trading":
       System.out.println("Trader has selected commodity trading option");
       break;
 default:
       throw new IllegalArgumentException();
 }
}



Example of String in Switch prior JDK7

Now let's see how it can be done prior to JDK 7 using if-else statement:

public static void tradingOptions(String trading) {

if (trading.equals("Stock Trading")) {
System.out.println("Trader has selected Stock Trading option");

} else if (trading.equals("Electronic Trading")) {
System.out.println("Trader has selected Electronic Trading option");

} else if (trading.equals("Algorithmic Trading")) {
System.out.println("Trader has selected Algorithmic Trading option");

} else if (trading.equals("Foreign exchange trading")) {
System.out.println("Trader has selected Foreign exchange Trading option");

} else if (trading.equals("commodity trading")) {
System.out.println("Trader has selected commodity trading option");

} else {
throw new IllegalArgumentException();
}
}

Overall allowing String into switch and case statement is not a wow feature but in my opinion, a very useful one and definitely makes coding easier and makes the code more readable by either removing the clumsy if-else statement. So I definitely vote plus one to JDK 7 String in switch feature and thanks to the guys involved in project coin for making life easier for java developers.

You also need to ensure that your JRE must-have source 1.7 otherwise if you try to run string in the switch in JRE less than 7 you will get the following error

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - strings in the switch are not supported in -source 1.6
  (use -source 7 or higher to enable strings in switch)
        at jdk7demo.JDK7Demo.tradingOptionChooser(JDK7Demo.java:34)
        at jdk7demo.JDK7Demo.main(JDK7Demo.java:25)


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 posts on Java you may find interesting:

9 comments :

Anonymous said...

Very nice feature of the so-much-awaited Java 7.
What do you think of using Strategy pattern to eliminate the need for a switch completely ?

siva477 said...

Its decrease so much complexicity of writing bulky code

Javin @ Stringbuffer vs StringBuilder said...

@Anonymous, Strategy pattern are good but some time it overkill for small need , So I think both have its place in terms of requirement.

Javin @ how to set classpath in java said...

@siva477, Indeed it removes all boiler plate code you need to write to get same effect. String in Switch is most overdue and it should have been included very early in java

Anonymous said...

Allowing String in Switch statements and Case statement is a great feature of Java7 and it reduces step to convert String and Integer which was the only way to achieve this before you Can use String in Switch case directly. Java7 is already getting very popular but problem is that not many webserver, IDE support Java7.

animateholic said...

switch case can be used for more complex and long conditional statement.

Anonymous said...

JDK7 Truly makes Java Really Easy...Thanks Man for guiding

~SS~ said...

Could you please talk about "The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements" ?????

Anonymous said...

In the previous versions of jdk(prior to jdk7), Enums can be used for String switch case.

Post a Comment