Junior
Կարո՞ղ է Java-ում օգտագործել տողեր switch կառուցվածքում:
sobes.tech AI
Պատասխան AI-ից
Այո։ Starting from Java 7, you can 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 done using the
equals()method, which is less efficient than primitive type comparison. - If the string in
caseor the value inswitchisnull, aNullPointerExceptionwill be thrown. Handle such cases either before theswitchor in thedefaultblock. - Strings in
casemust 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: The preferred way 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 between strings and 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.