Java12 new features - switch expression

Traditional switch expression drawbacks:

  • Matching top-down, if you forget to write the break, the back of the case statement will be executed whether or not to match;
  • All share a case statement block range, the variable name can not be repeated in a different case statement defined above;
  • You can not write multiple execution conditions consistent results in a case where;
  • Entire expression as a return value can not switch;

java 12 switch new features:

  • Use written in Java 12 Switch expressions, eliminating the break statement against the result of a small break and write errors.
  • While more case merge into one line, it is simple, clear and more elegant presentation logic branch, the specific wording of the statement is the case before a table becomes: case L ->, that is, if the conditions are matched case L, the implementation of the right label side code, code segments while the right side only tag expression, block, or throw statement.
  • In order to maintain compatibility, case conditional statements can still use the characters:, then fall-through rule is still valid, that can not be omitted original
    break statement, but the same can not be mixed in the structure of a Switch -> and: otherwise there will be Compile Error. Switch block and the local variables defined in a simplified, which limits the scope of the block, rather than spread throughout the Switch structure, do not have to assign a variable depending on the determination condition.
public class SwitchTest1 {
    public static void main(String[] args) {
            Week day = Week.FRIDAY;
            switch (day) {
            case MONDAY,FRIDAY, SUNDAY -> System.out.println(6);
            case TUESDAY -> System.out.println(7);
            case THURSDAY, SATURDAY -> System.out.println(8);
            case WEDNESDAY -> System.out.println(9);
            default -> throw new IllegalStateException("What day is today?" + day);
            }
        }
}


public class SwitchTest2 {
    public static void main(String[] args) {
            Week day = Week.FRIDAY;
            int numLetters = switch (day) {
                case MONDAY, FRIDAY, SUNDAY -> 6;
                case TUESDAY -> 7;
                case THURSDAY, SATURDAY -> 8;
                case WEDNESDAY -> 9;
                default -> throw new IllegalStateException("What day is today?" + day);
            };
        }
}

Guess you like

Origin www.cnblogs.com/androidsuperman/p/11704897.html