Starting from Java 7 release you can now use a string in the switch statement. On the previous version we can only use number or enum in the switch statement. The code below give you a simple example on it.
public class StringSwitchDemo {
public static void main(String[] args) {
StringSwitchDemo demo = new StringSwitchDemo();
String day = "Sunday";
switch (day) {
case "Sunday":
demo.doSomething();
break;
case "Monday":
demo.doSomethingElse();
break;
case "Tuesday":
case "Wednesday":
demo.doSomeOtherThings();
break;
default:
demo.doDefault();
break;
}
}
private void doSomething() {
System.out.println("StringSwitchDemo.doSomething");
}
private void doSomethingElse() {
System.out.println("StringSwitchDemo.doSomethingElse");
}
private void doSomeOtherThings() {
System.out.println("StringSwitchDemo.doSomeOtherThings");
}
private void doDefault() {
System.out.println("StringSwitchDemo.doDefault");
}
}
Monday, March 5, 2012
How do I use string in switch statement in Java?
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment