enum Status { PENDING, ACTIVE, ARCHIVED, DELETED }
// As an expression — assignable, returnable
String label(Status s) {
return switch (s) {
case PENDING -> "Not yet started";
case ACTIVE -> "In flight";
case ARCHIVED, DELETED -> "Gone"; // multi-label arm
};
}
// Multi-statement arm uses braces + yield
int weight(Status s) {
return switch (s) {
case PENDING -> 1;
case ACTIVE -> 10;
case ARCHIVED, DELETED -> {
log("counting an archived");
yield 0;
}
};
}
// Switch on type (Java 21+)
String describe(Object o) {
return switch (o) {
case Integer i when i > 0 -> "positive int " + i;
case Integer i -> "non-positive int " + i;
case String s -> "string of length " + s.length();
case null -> "null";
default -> "other";
};
}
void log(String s) { System.out.println(s); }
Create a free account and build your private vault. Share publicly whenever you want.