If I declare a variable before or without declaring enum constants in this way:
enum MyEnum
{
int i = 90;
}
It shows following compilation error.
MyEnum.java:3: <identifier> expected
{
^
MyEnum.java:4: ',', '}', or ';' expected
int i = 90;
^
MyEnum.java:4: '}' expected
int i = 90;
^
MyEnum.java:5: class, interface, or enum expected
}
^
4 errors
But if I declare an enum constant before declaring i
then it compiles fine.
Even the following code will compile fine:
enum MyEnum
{
;//put a semicolon
int i = 90;
}
Why java enum is designed in this way?
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
Enums are known as named constants. If we have some constants related to each other then we can use an enum to group all the constants.
Declaration of enum in Java: Enum declaration can be done outside a Class or inside a Class but not inside a Method.
valueOf(): This method is used to return an enum constant of the specified string value if it exists.
The ;
indicates the end of the enum identifiers list. Apparently you can have an empty enum list, but you must have one.
See 8.9.1 of the Java Language Specification:
8.9.1 Enum Constants
The body of an enum type may contain enum constants
Two mandatory parts of enum is:
You have to first declare enum identifiers list before enum body.
Here, ;
is showing the first part, as the first part is mandatory. If you ignore that, it will produce an compilation error. If you add ;
then it will compile as you fulfill both the criteria.
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