Enums in Java

Do not miss this exclusive book on Binary Tree Problems. Get it now for free.

Enum in Java is a special type of a class which can have constructors,methods, and instance variables. Enum contains a fixed set of constant. In Java, a list of prdefined values can be created using enums.

In order to use enum,you need to know how to declare it and access it.

Declaring Enums

  • You need to declare an enum to define a fixed set of constant.
  • An enum can be declared either inside the class or outside the class.

The following syntax is used to declare an enum:

enum enum-name{constant 1,constant 2,.....,constant n};

In the above syntax, enum-name is the name of the enum and constant 1,constant 2,and constant n are the constants in enum.

For example,to create an enumerated list, Mango ,you need to use the following code snippet:

enum Mango{Carrie, Fairchild, Haden};

In the preceeding code snippet, Mango is the name of the enum and Carrie,Fairchild, and Haden are the enum constants,which refer to the variety of the mango.

In Java, enums are similar to classes.Enums can have constructors,variables and methods.However,you cannot create an instance of an enum using the new keyword.The enum constructors get invoked when the enum constants are created, as these constants are treated as objects.For example, consider the following code:

class MangoVarieties
{
    enum Mango
    {
        Carrie(10), Fairchild(9), Haden(12);
        private int price;
        Mango(int p)
        {
            price=p;
        }
        int getPrice()
        {
            return price;
        }
    }
}

In the preceeding code snippet, the constructor accepts the prices of mango and assigns the value to the instance variable,price.The getPrice() method returns the price of the mango.

Accessing Enums

Once we have declare an enum,we can access it.You can either use an enum or its reference to access enum constants.An enum reference creation is similar to a variable creation. You need to use the following syntax to access an enum:

enum-name.enum-constant

or

enum-reference.enum-constant

In the above syntax,enum-name is the name of the enum and enum-constant is the enum constant.

enum-reference is the enum reference variable, which is similar to class reference.

Consider the following code snippet to access an enum constant and store it in an enum reference:

Mango p=Mango.Carrie;

In the above code snippet,an enum constant, Carrie, is accessed using the enum name, Mango.The accessed enum constant is assigned to an enum reference, p.

An example of enum in Java is:

package pkg;
enum Student
{
    Raj,Priya,Soni
}

public class Enum
{
    public static void main(String[] args)
    {
        Student s1=Student.Raj;
        Student s2=Student.Priya;
        Student s3=Student.Soni;
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
    }
}

Output:

Raj
Priya
Soni

To access all the values stored in an enum,Java provides the values() method.This method returns all the enum constants stored in an enum. For example, consider the following code:

enum Mango
{
    Carrie, Fairchild, Haden};
    class EnumTest
    {
        public static void main(String args[])
        {
          for(Mango p:Mango.values())
          System.out.println(p);
        }
    }
}

In the preceeding code, the for loop is used to traverse through the enum Mango.The values() method is used to return the enum constants stored in the enum.

Another example of enum in Java:

package opengenus;
enum Student
{
    Raj,Priya,Soni
}
public class Enum
{
    public static void main(String[] args)
    {
        Student arr[]=Student.values();    //declaring the array

        for(Student s:arr)
        {
            System.out.println(s+ "at index" +s.ordinal());
        }
    }
}

Output:

Raj at index 0
Priya at index 1
Soni at index 2

In the above example,ordinal() method is used, which returns the order of an enum instance.This represents the sequence in the enum declaration, where the initial constant is assigned an ordinal of '0'.....and so on.

Methods of Enum Class:

1. ordinal() Method

The ordinal() method returns the index value or position of an enum constant.
For example,

ordinal(hello)
//returns 0

2. compareTo() Method

The compareTo() method is used for comparing the enum constants based on their ordinal value.
For example,

public class CompareToEx{
public static void main(String args[]){
String s1="size";
String s2="size";
System.out.println(s1.compareTo(s2));
//returns 0 because they are equal

3. toString() Method

The toString() method returns the string representation of the enum constants.
For example,

enum Sports
{
    Badminton,Cricket,Football;
}
public class EnumDemo
{
    public static void main(String args[])
    {
        System.out.println("Playing "+ Sports.Badminton.toString());
        System.out.println("Playing "+ Sports.Cricket.toString());
        System.out.println("Playing "+ Sports.Football.toString());
    }
}
Output:
Playing Badminton
Playing Cricket
Playing Football

4. valueOf() Method

The valueOf() method takes a string and returns an enum constant having the same string.
For example,

enum Birds
{
    Peacock,Parrot,Eagle,Sparrow;
}

public class Enumdemo
{
public static void main(String[] args)
{
    System.out.println("National Bird of India is:");

    for(Birds b:Birds.values())
    {
        int i=b.ordinal()+1;
        System.out.println(i+" "+b);
    }
    Birds b=Birds.valueOf("Peacock");
    System.out.println("\nAns:"+b);
}
}
Output:
National Bird of India is:
1 Peacock
2 Parrot
3 Eagle
4 Sparrow

Ans: Peacock

5. values() Method

The values() method returns an array of enum type containing all the enum constants.
For example,

class Enumdemo
{
public enum Days{Monday,Tuesday,Wednesday,Thursday}

public static void main(String[] args)
{
    for(Days d:Days.values())
        System.out.println(d);
}
}

Output:

Monday
Tuesday
Wednesday
Thursday

6. name() Method

The name() method returns the defined name of an enum constant in string form.
For example,

enum Sports
{
    Badminton(2),Cricket(3),Football(0);
    int win;
    Sports(int w)
    {
        win=w;
    }

    int getwin()
    {
        return win;
    }
}
public class Enumdemo
{
    public static void main(String[] args)
    {
        for(Sports w:Sports.values())
        {
            System.out.println("Person has win "+w.getwin()+"matches of "+w.name());
        }
    }
}

Output:

Person has win 2 matches of Badminton
Person has win 3 matches of Cricket
Person has win 0 matches of Football

Learn more:

Sign up for FREE 3 months of Amazon Music. YOU MUST NOT MISS.