1

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";
        };
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
vdmclcv
  • 135
  • 12
  • 6
    https://docs.oracle.com/en/java/javase/13/language/switch-expressions.html: "To specify their value, use the new yield statement instead of the break statement." – Andy Turner Apr 05 '21 at 12:38

2 Answers2

7

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";
};
M A
  • 71,713
  • 13
  • 134
  • 174
  • 1
    Thanks a lot. I am aware of arrow notation and was able to produce it without error. I was not aware about yield. Strange, I'm learning with oReilly Learning Java book and it claims to be fully updated for Java 14. That was misleading. Your answer however sorted my issue. Thank you. – vdmclcv Apr 05 '21 at 12:58
  • Nice! @vdmclcv - You can also check [What are switch expressions and how are they different from switch statements?](https://stackoverflow.com/q/65657169/10819573) – Arvind Kumar Avinash Apr 05 '21 at 13:04
-2

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

Yegorf
  • 400
  • 2
  • 11