The Enum type in Java

There are situations in programming where you require variable values to be among the pre-defined constants. For example, month names (Jan, Feb, Mar), day names (Sat, Sun, Mon), compass directions (North, East, West, South), marital status (married, single, widowed etc.) and so on.

There are other ways to restrict it, Java Enum is one of the better solutions to do it in Java programming.

An example of enum

A few important points about enum are:

  • An enum is a special data type.
  • The enum in Java enables a variable to allow using the predefined constants.
  • That means any value assigned to the variable must be equal to one of the predefined constant in the enumeration.
  • The Enum is type-safety. You can ensure to limit for the particular set of values.
  • Java enum can be used with the switch decision-making statement like primitive data types, which is quite useful.
  • Names of the enumeration data type field are in uppercase letters, as such these are constants.
  • Enum is like a class or interface, so it can include methods or other fields as well.
  • The constants in enum are static and final implicitly i.e. once created it cannot be changed.
  • Enum type was introduced in JDK 1.5.

How to declare an enum

In Java, an enumeration is declared by using the enum keyword as below:

public enum Month {JAN, FEB, MAR, APR}

An enum example

The example below declares a month enum.

First declaring enum Month

Experience this online

Code to work with enum

 

Experience this online

The output will be:

This is January.

This is February.

This is April

This is May

This is June

This is July

The example showed how to use the enum, by first declaring a Month enum and then the lower part of the code uses Java Switch statement where Java enum Month constant values used as the switch case.

Read Further: Java ArrayList