Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't an enum value be fully qualified in a switch statement?

Tags:

(note: edited question; the prior intent was not clear)

Consider this code:

public final class Foo {     private enum X     {         VALUE1, VALUE2     }      public static void main(final String... args)     {         final X x = X.VALUE1;          switch (x) {             case VALUE1:                 System.out.println(1);                 break;             case VALUE2:                 System.out.println(2);         }     } } 

This code works fine.

However, if I replace:

case VALUE1: // or VALUE2 

with:

case X.VALUE1: // or X.VALUE2 

then the compiler complains:

java: /path/to/Foo.java:whatever: an enum switch case label must be the unqualified name of an enumeration constant

SO suggests an answer with this quote from the JLS:

(One reason for requiring inlining of constants is that switch statements require constants on each case, and no two such constant values may be the same. The compiler checks for duplicate constant values in a switch statement at compile time; the class file format does not do symbolic linkage of case values.)

But this does not satisfy me. As far as I am concerned, VALUE1 and X.VALUE1 are exactly the same. The quoted text does not explain it at all for me.

Where in the JLS is it defined that enum values in switch statements have to be written this way?

like image 276
fge Avatar asked Jul 20 '13 17:07

fge


People also ask

Can enums be used in switch statements?

An Enum keyword can be used with if statement, switch statement, iteration, etc. enum constants are public, static, and final by default. enum constants are accessed using dot syntax. An enum class can have attributes and methods, in addition to constants.

Can we use enum in switch case in C?

We can use enums in C for multiple purposes; some of the uses of enums are: To store constant values (e.g., weekdays, months, directions, colors in a rainbow) For using flags in C. While using switch-case statements in C.

Can you switch on an enum in Java?

You definitely can switch on enums. An example posted from the Java tutorials.

Can enum be declared in interface?

Yes, Enum implements an interface in Java, it can be useful when we need to implement some business logic that is tightly coupled with a discriminatory property of a given object or class. An Enum is a special datatype which is added in Java 1.5 version.


1 Answers

SwitchLabel expects an EnumConstantName, which is defined as the enum constant identifier, which is unqualified:

EnumConstant:
Annotationsopt Identifier Argumentsopt ClassBodyopt

like image 66
assylias Avatar answered Sep 22 '22 14:09

assylias