top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Enumerations in java

0 votes
400 views

Enumerations in Java

An Enumeration is similar to a class that contains only constant values. Remember a constant represents a fixed value and it does not change. For example, as there are fixed number of days in a week, namely Sunday, Monday, Tuesday, Wednesday, Thursday, Friday and Saturday, you can take these days as constants and construct the following enumeration called days:

enum Days{

            SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY

}

An enumeration is always represented by the word enum, followed by the name of the enumeration, which in this case is Days. After this, you need to write the constant within a pair of {}. In the preceding code snippet, the constant are written in capital letters; however, you can also use small letters to represent constants. Each of these can be referred by its individual name, such as Days.SUNDAY, Days. MONDAY.

The following code snippet shows another enumeration, Color, with some color names as constants:

enum Color{

            RED, GREEN, BLUE, WHITE, BLACK

}

The position of constants inside an enumeration will be counted from 0 onwaards. For example, in the preceding code snippet, the 0 position is given to RED, 1 to GREEN, and 2 to BLUE.

You can also retrieve all the constants from an enumeration by using the values() method. It is a static method, which returns all the constants into an array of enumeration-type.

The syntax to use the value() method is given in the following code snippet:

Days a || days[] = Days. Values();

In the preceding code snippet, the values() method is used on Days enumeration which returns all the constants into alldays[] array, so that alldays[0] represents SUNDAY, alldays[1] represents MONDAY, and so on. These values can be retrieved separately again from alldays[] using a for each loop, as shown in the following snippet:

for( Days.d: alldays)

System.out.println(d);

Example: Write a Java program to declare an enumeration, Days, and retrieve all days from it using the values() method:

//Create an enumeration with day names

enum Days

{

    Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday

}

class DisplayEnum

{

    public static void main(String args[])

    {

         //using values() method retrieve all enum constants into all days[] array

          Days alldays[] = Days. Values();

        //using for each loop, retrieve the enum constants from alldays[] and display them

         for (Days d: alldays)

         System.out.println(d);

    }

}

 

The output of the above program is as follow:

Sunday

Monday

Tuesday

Wednesday

Thursday

Friday

Saturday

Go through this video:

posted Feb 5, 2018 by Ammy Jack

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button

...