Example of String in Switch prior JDK7 using enum:
public class StringSwitchDemo {
public enum Day
{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY;
}
public static void main(String[] args) {
String str = "SUNDAY";
switch (Day.valueOf(str))
{
case SATURDAY:
case SUNDAY:
System.out.println("Sunday");
// weekend processing ...
break;
default:
// weekday processing ...
System.out.println("default");
break;
}
}
}
Output: Sunday
Example of String in Switch in JDK7
JDK 7 has made an important enhancement in there support of String, now you can use String in switch and case statement
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();
}
}
Try executing above code in below link:
http://www.compileonline.com/compile_java_online.php
public class StringSwitchDemo {
public enum Day
{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY;
}
public static void main(String[] args) {
String str = "SUNDAY";
switch (Day.valueOf(str))
{
case SATURDAY:
case SUNDAY:
System.out.println("Sunday");
// weekend processing ...
break;
default:
// weekday processing ...
System.out.println("default");
break;
}
}
}
Output: Sunday
Example of String in Switch in JDK7
JDK 7 has made an important enhancement in there support of String, now you can use String in switch and case statement
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();
}
}
http://www.compileonline.com/compile_java_online.php
No comments:
Post a Comment