gersseba
gersseba

Reputation: 21

Why is chaining labels in the switch syntax allowed and what does it do?

I recently discovered, that in a java switch statement, multiple labels can be chained, but for no apparent effect. And it even allows labels that do not exist. For example you can do this: case ENUM_VALUE_1:ENUM_VALUE_2:, or even this case ENUM_VALUE_1:foobar:barfoo:. As long as it ends with a colon, any value seems to be accepted. First I though this might be a different way of grouping multiple cases, but that does not seem to be working. So I ran the following test

public class Main {

public enum TestEnum {
    A,
    B
}

public static void main(String[] args) {
    TestEnum testEnum = TestEnum.B;

    switch (testEnum) {
        case A: System.out.println("Test 1: Case 1"); break;
        case B: System.out.println("Test 1: Case 2"); break;
    }

    switch (testEnum) {
        case A: System.out.println("Test 2: Case 1"); break;
        case B:A: System.out.println("Test 2: Case 2"); break; // Label A is already used in enum
    }

    switch (testEnum) {
        case A:B: System.out.println("Test 3: Case 1"); break; // Label B is already used in enum
        case B: System.out.println("Test 3: Case 2"); break;
    }

    switch (testEnum) {
        case A:BARFOO: System.out.println("Test 4: Case 1"); break; // Label BARFOO does not exist
        case B:FOOBAR: System.out.println("Test 4: Case 2"); break; // Label FOOBAR does not exist
    }

    switch (testEnum) {
        case A:B: System.out.println("Test 5: Case 1"); break;
    }
}}

I ran it in java 11 and 17 and the output in both versions is:

Test 1: Case 2
Test 2: Case 2
Test 3: Case 2
Test 4: Case 2

I would have expected that only test 1 and 5 actually compile, but they all compile and it seems that everything after the actual label is just ignored.

I doubt this is an oversight, so what am I missing?

Upvotes: 1

Views: 161

Answers (1)

khelwood
khelwood

Reputation: 59111

Where in your code you have something like this:

case A:BARFOO:

BARFOO: isn't a switch case. It's nothing to do with the switch mechanics. It's just a label. You're allowed to label any statement, but it's not always useful. It's typically used for loops: e.g.

outerloop:
while (true) {
    while (true) {
        break outerloop;
    }
}

If you actually wanted to group together multiple cases, you could write it like:

case A: case B:
    ...
    break;

And as Jesper mentions in the comments, more recent versions of Java also support a switch expression, under which the syntax is:

case A, B -> ...

Upvotes: 4

Related Questions