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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
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"); } } |