How do I use string in switch statement?

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;
        }
    }
}

How do I use enum in switch statement?

This example show you how to use enumeration or enum type in a switch statement.

package org.kodejava.basic;

public enum RainbowColor {
    RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET
}
package org.kodejava.basic;

public class EnumSwitch {
    public static void main(String[] args) {
        RainbowColor color = RainbowColor.INDIGO;

        EnumSwitch es = new EnumSwitch();
        String colorCode = es.getColorCode(color);
        System.out.println("ColorCode = #" + colorCode);
    }

    public String getColorCode(RainbowColor color) {
        String colorCode = "";

        // We use the switch-case statement to get the hex color code of our
        // enum type rainbow colors. We can pass the enum type as expression
        // in the switch. In the case statement we only use the enum named
        // constant excluding its type name.
        switch (color) {
            // We use RED instead of RainbowColor.RED
            case RED -> colorCode = "FF0000";
            case ORANGE -> colorCode = "FFA500";
            case YELLOW -> colorCode = "FFFF00";
            case GREEN -> colorCode = "008000";
            case BLUE -> colorCode = "0000FF";
            case INDIGO -> colorCode = "4B0082";
            case VIOLET -> colorCode = "EE82EE";
        }
        return colorCode;
    }
}