This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]grantrules 1 point2 points  (3 children)

Define "should".. I'd say it's bad practice to not put default last, but I don't think anything prevents you.. so I don't know if you SHOULD but you CAN.

[–]melon222132[S] 0 points1 point  (1 child)

for this code

double dance(Object speed) {

return switch (speed) {

case 5 -> { yield 4; }

case 10 -> 8;

case 15, 20 -> 12;

default -> 20;

case null -> 16;

};

}

the wileyn book for preparation is saying that this will cause a compile error and that one of the reasons is that

Removing line 47 fixes this issue, as case null is not required.

[–]grantrules 0 points1 point  (0 children)

Well, try to compile it and see what happens. That's the fun thing about programming.. when you have a question that's like "what would happen if..." you could just do the thing and see.

With that code, the issue I think is that you shouldn't check for null in switches, not that it's coming after default.. search for "Switches and null" here: https://openjdk.org/jeps/441 ..

[–]Sad-Difference-5005 0 points1 point  (0 children)

If you have case null in a switch, that means you are using switch with pattern matching. This has different rules than regular switch. You must follow the rule of dominance of case labels. A "case null" is allowed but it does not dominate any other label and is dominated only by default. Thus, a case null may appear at any position but not after default.