Starting from Java 7 release you can now use a String
in the switch
statement. On the previous version we can only use constants type of byte
, char
, short
, int
(and their corresponding reference / wrapper type) or enum
constants in the switch
statement.
The code below give you a simple example on how the Java 7 extended to allow the use of String
in switch
statement.
package org.kodejava.basic;
public class StringInSwitchExample {
public static void main(String[] args) {
String day = "Sunday";
switch (day) {
case "Sunday":
System.out.println("doSomething");
break;
case "Monday":
System.out.println("doSomethingElse");
break;
case "Tuesday":
case "Wednesday":
System.out.println("doSomeOtherThings");
break;
default:
System.out.println("doDefault");
break;
}
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024