Switch Expression Enhancements

Switch expressions were introduced in Java 12 as a preview feature. Over the last few months, the community sent feedback to Oracle and now in Java 13, they’ve released some improvements programmers were asking for.

Let’s quickly review the switch expressions that were introduced in Java 12 and then talk about improvements that Oracle has made for this release.

Switch was always an error-prone component and generally rarely used in everyday development. Having to type break; at the end of every case always seemed like boilerplate. Java 12 addressed this by doing two things: it made switch an expression (not just a statement), which means that it now returns a value that can be assigned to a variable, or serve as a return statement, or any other use case you might think of. The second thing Java 12 did was get rid of annoying break; by making switch not fall-through between cases when you use the new syntax case -> instead of case: .

Of course, every new Java version is backward-compatible, using old syntax gives you old fall-through behavior. None of the legacy code is broken or has changed behavior.

// Legacy Switch Statement

private String javaReleaseDate(int version) {

String result = "TBD";

switch (version){

case 12:

result = "19.3";

break;

case 13:

result = "19.9";

break;

};



return result;

}

// Arrow Syntax Switch Expression // no fall-through

private String javaReleaseDate(int version) {

return switch (version) {

case 12 -> "19.3";

case 13 -> "19.9";

default -> "TBD";

};

}

Due to community feedback on switch expressions, in Java 13 if you want to use switch as an expression and not a statement, and you want to use colon syntax, the keyword `break` is replaced with the keyword yield . This change removes confusion and makes it obvious if you are using switch as an expression or as a statement, making it way less likely to unintentionally use something you didn’t want. The yield statement is very similar to the return statement; when case is matched it returns the current branch result without the fall-through.

// Switch Expression using yield over break

private String javaReleaseDate(int version) {

return switch (version){

case 12: yield "19.3";

case 13: yield "19.3";

default: yield "TBD";

};

}

This feature is still in preview, so, in coming Java releases we might see further changes and improvements.