java Enum – What is enum in Java and how to use it with examples

Java Enum Type

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, Enum is one of the better solution to do it.

A few important points about enum:

  • An enum is a special data type
  • enum enables for a variable to allow using predefined constants
  • That means any value assigned to variable must be equal to one of predefined constant in enumeration
  • Enums are type-safety. You can ensure to limit for particular set of values
  • Enums can be used with <switch> decision making statements like primitive data types, which is quite useful
  • Names of enumeration data type field are in uppercase letters, as such these are constants
  • Enum are like class or interface in Java 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 was introduced in JDK 1.5

How to declare an enum

In java an enumeration is declared by using enum keyword as below:

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

Example of using enum with month name example

The example below declare a month enum.

First declaring enum Month

See graphic of above example

Code to work with enum

See graphic of above example

The output will be:

This is January.

This is February.

This is April

This is May

This is June

This is July

Also see

Was this article helpful?

Related Articles

Leave A Comment?