You don't need breaks with enhanced switch, do you?

My IntelliJ IDEA suggested replacing a regular switch with an “enhanced” switch. Initially, as usual, my switch had breaks. After IntelliJ’s modification, however, the switch had no breaks. What made things more complicated, googling suggested you need them even if your switch is “enhanced”

Do you need breaks when using an “enhanced” switch statement?

Before:

public void romanToArab() {
        switch (stringValue) {
            case "I":
                doubleValue = 1;
                break;
            case "II":
                doubleValue = 2;
                break;
            case "III":
                doubleValue = 3;
                break;
            case "IV":
                doubleValue = 4;
                break;
            case "V":
                doubleValue = 5;
                break;
            case "VI":
                doubleValue = 6;
                break;
            case "VII":
                doubleValue = 7;
                break;
            case "VIII":
                doubleValue = 8;
                break;
            case "IX":
                doubleValue = 9;
                break;
            case "X":
                doubleValue = 10;
                break;
            default:
                dontKnow = true;
        }
    }

After:

public void romanToArab() {
        switch (stringValue) {
            case "I" -> doubleValue = 1;
            case "II" -> doubleValue = 2;
            case "III" -> doubleValue = 3;
            case "IV" -> doubleValue = 4;
            case "V" -> doubleValue = 5;
            case "VI" -> doubleValue = 6;
            case "VII" -> doubleValue = 7;
            case "VIII" -> doubleValue = 8;
            case "IX" -> doubleValue = 9;
            case "X" -> doubleValue = 10;
            default -> dontKnow = true;
        }
    }

If in doubt, refer to the documentation:

1 Like