Java: Switch Expression
Note: Not to be confused with switch statements. (What's the difference between statements and expressions?)
Let's start with an example:
int i = switch (someString) {
case "one" -> 1;
case "two" -> 2;
case "three" -> 3;
default -> -1;
};
You can switch on integers, strings and enums.
Need to cover all cases
int i = 1;
String str = switch (i) {
case 1 -> "one";
case 2 -> "two";
case 3 -> "three";
}
Multiple case expressions
You can have multiple case expressions in one case line:
String str = switch (i) {
case 1, 2, 3 -> "one, two, or three"
default -> "Something else";
}
Blocks statements and break
You can use break
to "return" values.
This allows for use of block statements.
String str = switch (i) {
case 1 -> "one";
case 2 -> break "two";
case 3 -> {
System.out.println("Third case!");
break "three";
}
default -> "Something else";
};
Throw
Statements must be wrapped in { ... }
except for a single throw
statement.
int i = switch (someString) {
case "one" -> 1;
case "two" -> 2;
case "three" -> 3;
default -> throw new IllegalArgumentException();
};
Colon syntax
Colon syntax allows for statements even without { ... }
.
Cases will fall through.
You must use break.
String str = switch (i) {
case 1:
System.out.println("One");
System.out.println("Falling through!");
case 2:
break "Two";
default:
break "Something else";
};
You can not mix arrow and colon syntax in the same switch.
Enhanced Switch Statement
Switch expressions should not be confused with switch statements. (See Statements vs Expressions.)
The arrow syntax can be used in switch statements too, in which case fall through is disabled and break
is disallowed.
See article Switch Statement.