Tuesday 26 September 2017

Enum ordinal() method

Java.lang.Enum.ordinal() Method

The java.lang.Enum.ordinal() method returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero).

Declaration
Following is the declaration for java.lang.Enum.ordinal() method

public final int ordinal()

Parameters
NA

Return Value
This method returns the ordinal of this enumeration constant.

Exception
NA

Example
The following example shows the usage of java.lang.Enum.ordinal() method.

enum Country{
   India(9), Nepal(8),Shrilanka(5);
   int gdp;
   Mobile(int gdp) {
      this.gdp= gdp;
   }
   int getGdp() {
      return gdp;
   } 
}

public class EnumDemo {

   public static void main(String args[]) {
      System.out.println("CellPhone List:");
      for(Country c : Country.values()) {
         System.out.println("Gdp of"+c+ "is"+ c.getGdp() );
      }
      Country c = Country.India;
      System.out.println("The ordinal is = " + c.ordinal());
      System.out.println("Country= " + c.name());                      
   }
}

No comments:

Post a Comment