Switch to Switch Expressions

class NameBadge {

  enum Rank {
    PILOT,
    COMMANDER,
    RESEARCHER
  }

  String name;
  Rank rank;

  public String toString() {
    String result;
    switch (rank) {
      case COMMANDER:
        result = "***";
        break;
      case PILOT:
        result = "**";
        break;
      case RESEARCHER:
      default:
        result = "*";
    }
    return name + " " + result;
  }
}

This classic switch statement assigns a variable in every branch. That needs a declaration up front, a break after every case, and a default branch, even though every value of Rank is already covered, because otherwise the compiler complains that result might not be initialized.

It's easy to get wrong. Forget one break, and the code silently falls through into the next case. And the default branch hides mistakes: when someone adds a new rank, it quietly gets one star instead of a compile error.

class NameBadge {

  enum Rank {
    PILOT,
    COMMANDER,
    RESEARCHER
  }

  String name;
  Rank rank;

  public String toString() {
    return name + " " + switch (rank) {
      case COMMANDER -> "***";
      case PILOT -> "**";
      case RESEARCHER -> "*";
    };
  }
}

Since Java 14, switch can be an expression that returns a value directly. With the arrow syntax, each case maps to its result, there's no fall-through, so no break. The whole method becomes a single return statement, and the temporary variable is gone.

Since every enum constant is covered, the compiler accepts the switch without a default branch. Even better, when someone adds a new rank later, this code stops compiling until the new case is handled. The compiler now checks what the default branch used to hide.