Sobes.tech
Junior

Can strings be used in switch statements in Java?

sobes.tech AI

Answer from AI

Yes. Starting from Java 7, it is possible to use String objects in switch statements.

// Example of using strings in switch
String status = "ACTIVE";
switch (status) {
    case "ACTIVE":
        System.out.println("Status: Active");
        break;
    case "PENDING":
        System.out.println("Status: Pending");
        break;
    case "DELETED":
        System.out.println("Status: Deleted");
        break;
    default:
        System.out.println("Unknown status");
}

Important points when using strings in switch:

  • String comparison is performed using the equals() method, which is less efficient than primitive type comparison.
  • If the string in case or the value in switch is null, a NullPointerException will be thrown. Handle such cases either before the switch or in the default block.
  • Strings in case must be compile-time constants.
  • Case sensitivity matters. "Active" is not equal to "active".

Alternatives to using strings in switch:

  • if-else if: The most straightforward alternative.
  • Enum: Preferred for a limited set of possible values. Ensures type safety and better code management.
// Example of using enum
public enum Status {
    ACTIVE, PENDING, DELETED
}

// ...

Status currentStatus = Status.ACTIVE;
switch (currentStatus) {
    case ACTIVE:
        System.out.println("Status: Active");
        break;
    case PENDING:
        System.out.println("Status: Pending");
        break;
    case DELETED:
        System.out.println("Status: Deleted");
        break;
    default:
        System.out.println("Unknown status"); // Usually not needed with enum
}
  • Map: Can be useful if the mapping of strings to actions is more dynamic or voluminous.
// Example of using Map
Map<String, Runnable> actions = new HashMap<>();
actions.put("ACTIVE", () -> System.out.println("Status: Active"));
actions.put("PENDING", () -> System.out.println("Status: Pending"));
actions.put("DELETED", () -> System.out.println("Status: Deleted"));

// ...

String status = "ACTIVE";
actions.getOrDefault(status, () -> System.out.println("Unknown status")).run();

The choice among these approaches depends on the specific task, code readability, and the need for type safety. For a limited and fixed set of string values, Enum is usually the best solution.

Can strings be used in switch statements in Java… - sobes.tech