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 create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023