Enums in Java

An enum type is a special data type in java used to define collections of constants. More precisely as of Java 5, Java lets you restrict a variable to have one of only a few pre-defined values – in other words, one value from an enumerated list called enums.

Enum Example

In java you define an enum type using the  enum  keyword. For example, you would specify review status of an article using enum type as:

The basic components of an  enum  are its constants. And it’s not required to use caps for all the enum constants, but it’s good idea to use caps as per Oracle’s code convention.

Enum outside a class example:

Here is an example, which shows how to use enum outisde a class

The above code can be part of single file. But the file must be named ReviewTest.java because that’s the name of the  public  class in the file.

Enum inside a class example:

Here is an example, which shows how to use enum inside a class

The important point that you should note is  enums  can be declared as their own class or enclosed in another class, but the syntax for accessing  enum  members depends on where the  enum  is declared.

  • You cannot declare  enums  in methods.
  • It is optional to put semicolon  ;  at the end of  enum  declaration.
What is getting created when you create enum ?

Please note that  enums  are not  strings  or ints . In the above example each of the enumerated  ReviewStatus  types is the instance of ReviewStatus . You can think of  enum as a kind of class which looks something like the following

Note that each of enumerated values are represented as  static  and  final (constants) and each  enum  value knows its index or position. You can think of the ReviewStatus enums as existing in an array of type ReviewStatus.

Leave a Reply

Notify of