StatementSwitchToExpressionSwitch
This statement switch can be converted to an equivalent expression switch

Severity
WARNING

The problem

We’re trying to make switch statements simpler to understand at a glance. Misunderstanding the control flow of a switch block is a common source of bugs.

Statement switch statements:

Expression switch statements

Examples

enum Suit {HEARTS, CLUBS, SPADES, DIAMONDS}

private void foo(Suit suit) {
  switch(suit) {
    case HEARTS:
System.out.println("Red hearts");
    case DIAMONDS:
System.out.println("Red diamonds");
    case SPADES:
      // Fall through
    case DIAMONDS:
      bar();
      System.out.println("Black suit");
    }
}

Which can be simplified into the following expression switch:

enum Suit {HEARTS, CLUBS, SPADES, DIAMONDS}

private void foo(Suit suit) {
  switch(suit) {
    case HEARTS -> System.out.println("Red hearts");
    case DIAMONDS -> System.out.println("Red diamonds");
    case CLUBS, SPADES -> {
      bar();
      System.out.println("Black suit");
    }
  }
}

Here’s an example of a complex statement switch with conditional fall-through and complex control flows. How many potential execution paths can you spot?

enum Suit {HEARTS, CLUBS, SPADES, DIAMONDS}

private int foo(Suit suit){
  switch(suit) {
    case HEARTS:
      if (bar()) {
        break;
      }
      // Fall through
    case CLUBS:
      if (baz()) {
        return 1;
      } else if (baz2()) {
        throw new AssertionError(...);
      }
      // Fall through
    case SPADES:
      // Fall through
    case DIAMONDS:
      return 0;
  }
  return -1;
}

Suppression

Suppress false positives by adding the suppression annotation @SuppressWarnings("StatementSwitchToExpressionSwitch") to the enclosing element.