
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 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)
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 post on Java you may find interesting:
No comments:
Post a Comment