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

420 Views Asked by At

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";
        };
2

There are 2 best solutions below

2
M A On BEST 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";
};
4
Yegorf On

For JDK < 13

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

For JDK > 13:

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

Your example - is the combination of sitch statement and expression :)