Switch expressions: Why does Java consider my break – String lines not to be statements?

Trying to understand switch expression and came up with the following code. In fact I get “not a statement” error for all “break – String” combinations. What am I doing wrong?

String i = switch(value) {
            case 0:
                break "Value is 0";
            case 1:
                break "Value is 1";
            case 2:
                break "Value is 2";
            default:
                break "Unknown value";
        };

Answer

The correct keyword to use is yield to return a value in a switch expression: it was introduced as an enhancement in JDK 13. Alternatively since your expressions are all simple you can use the shorthand arrow notation:

String i = switch(value) {
    case 0 -> "Value is 0";
    case 1 -> "Value is 1";
    case 2 -> "Value is 2";
    default -> "Unknown value";
};