(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?
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.
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.
You definitely can switch on enums. An example posted from the Java tutorials.
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.
SwitchLabel
expects an EnumConstantName
, which is defined as the enum constant identifier, which is unqualified:
EnumConstant:
Annotationsopt Identifier Argumentsopt ClassBodyopt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With