Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the enum constants must be declared before any other variables and methods declaration in an enum type?

Tags:

java

syntax

enums

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?

like image 566
Vishal K Avatar asked Jun 27 '13 08:06

Vishal K


People also ask

What is the purpose of using enum?

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.

Should enums be constants?

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.

Can enum be declared in a method?

Declaration of enum in Java: Enum declaration can be done outside a Class or inside a Class but not inside a Method.

Which of the following method can be used to get enum constants?

valueOf(): This method is used to return an enum constant of the specified string value if it exists.


2 Answers

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

like image 145
Jeff Foster Avatar answered Oct 26 '22 15:10

Jeff Foster


Two mandatory parts of enum is:

  1. enum identifiers;
  2. enum body.

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.

like image 41
Shreyos Adikari Avatar answered Oct 26 '22 14:10

Shreyos Adikari