简体   繁体   中英

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

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

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:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM