Careeroza
Switch on Strings and Enums
Switch on a String
Example
String cases are compared with equals() (case-sensitive).
public class Main {
public static void main(String[] args) {
String[] commands = {"start", "stop", "STATUS", "jump"};
for (String cmd : commands) {
String reply = switch (cmd.toLowerCase()) {
case "start" -> "Server starting...";
case "stop" -> "Server stopping...";
case "status" -> "Server is running";
default -> "Unknown command: " + cmd;
};
System.out.println(reply);
}
}
}Output
Server starting... Server stopping... Server is running Unknown command: jump
Switch on an Enum
Example
An enum is a fixed set of named constants (more in the medium level). Inside the switch you write the constant name without the enum prefix. If all values are covered, no default is needed.
public class Main {
enum OrderStatus { PLACED, PACKED, SHIPPED, DELIVERED }
public static void main(String[] args) {
for (OrderStatus status : OrderStatus.values()) {
String message = switch (status) {
case PLACED -> "We have received your order";
case PACKED -> "Your order is packed";
case SHIPPED -> "Your order is on the way";
case DELIVERED -> "Delivered. Enjoy!";
};
System.out.println(status + ": " + message);
}
}
}Output
PLACED: We have received your order PACKED: Your order is packed SHIPPED: Your order is on the way DELIVERED: Delivered. Enjoy!