Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – Enumerations

In Java, enumeration is a group of constants. It is far different from enum of old languages like C & C++.
It can contain variables, methods & constructors like normal classes.

An enum keyword is used to create enumeration.

Example of enumeration

 enum Fruits
{
    Apple, Banana, Pineapple, Papaya, Strawberry
}

Enumeration variable

Declaring enumeration variable is same as declaring variable in a class.

Example of enumeration variable

 Fruits f;
f = Fruits.Apple;

                                                                                OR

 Fruits f = Fruits.Pineapple;

Simple demonstration of Fruits enumeration

 enum Fruits 
 {
     Apple, Banana, Pineapple, Papaya, Strawberry
 }

 class EnumDemonstration 
 {
     public static void main(String args[])
     {
         Fruits f;
         f = Fruits.Pineapple; // assigns value of Pineapple
         System.out.println("Value of f :: "+f);
		
         f = Fruits.Strawberry; // assigns value of Strawberry
         System.out.println("Value of f :: "+f);
     }
 }

Output

Value of f :: Pineapple
Value of f :: Strawberry

Inside enumeration toString() method is defined to return the value of the enumeration constant.

Useful methods for Enum

The valueOf() method

This method returns the enumeration constant with value same as specified string.

Example

 enum Fruits
 {
     Apple, Banana, Pineapple, Papaya, Strawberry
 }

 class ValueOfDemo 
 {
     public static void main(String args[]) 
     {
         Fruits f;
        
         f = Fruits.valueOf("Banana");
         System.out.println(f);
        
         f = Fruits.valueOf("Papaya");
         System.out.println(f);
        
         f = Fruits.valueOf("Apple");
         System.out.println(f);
     }
 }

Output

Banana
Papaya
Apple

The values() method

This method returns all enumeration constants.

Example

 enum Fruits 
 {
    Apple, Banana, Pineapple, Papaya, Strawberry
 }

 class ValuesDemo 
 {
     public static void main(String args[])
     {
         Fruits f[] = Fruits.values();
         for(Fruits fr:f)
         {
             System.out.println(fr);
         }
     }
 }

Output

Apple
Banana
Pineapple
Papaya
Strawberry

The ordinal() method

This method returns the position of an enumeration constant in the enum.
A position is counted from zero.
The position of enumeration constant is known as its ordinal value.

Example

 enum Fruits 
 {
     Apple, Banana, Pineapple, Papaya, Strawberry
 }

 class OrdinalValueDemo 
 {
     public static void main(String args[]) 
     {
         for(Fruits f:Fruits.values())
         {
             System.out.println("Ordinal value of "+f+" :: "+f.ordinal());
         }
     }
 }

Output

Ordinal value of Apple :: 0
Ordinal value of Banana :: 1
Ordinal value of Pineapple :: 2
Ordinal value of Papaya :: 3
Ordinal value of Strawberry :: 4

 

Leave a reply