0 votes
in JAVA by

With Java 12, the beta switch expression will improve coding by extending the switch statement, enabling its use as either a statement or an expression. It will let both forms use either the traditional or simplified scoping and control flow behavior. This will help simplify the code and also pave the way for the use of pattern matching in a switch.

Java developers are enhancing the Java programming language to use pattern matching to resolve several issues with the current switch statement. This includes: default control flow behavior of switch blocks, default scoping switch block (a block considered as a single scope) and switch working only as a statement.

In Java 11, the switch statement tracks C and C++ programming languages, and by default, uses the fall-through semantics. While the traditional control flow is beneficial when writing low-level codes, the error-prone nature will soon outweigh its flexibility as the switch is adopted in higher-level contexts.

Java 11

int numberOfLetters;

switch (fruit) {
case PEAR:
    numberOfLetters = 4;
    break;
case APPLE:
case GRAPE:
case MANGO:
    numberOfLetters = 5;
    break;
case ORANGE:
case PAPAYA:
    numberOfLetters = 6;
    break;
default:
    throw new IllegalStateException (“Wut + fruit);
}

Java 12

int numberOfLetters = switch (fruit) {
    case PEAR -> 4;
    case APPLE, MANGO, GRAPE -> 5;
    case ORANGE, PAPAYA -> 6;
}

As you can see, switch expressions bring clearer, cleaner, and safer code.

Related questions

0 votes
asked Apr 21, 2020 in JAVA by Hodge
+2 votes
asked Feb 8, 2020 in JAVA by rahuljain1
...