Tuesday 3 November 2015

Java.lang.Enum.ordinal() Method

Java.lang.Enum.ordinal() Method

The 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).

public final int ordinal()



public class EnumOrdinal {

     // enum showing Laptop prices
     enum Laptop {
           Dell(1600), HP(1500), Lenovo(1000);

           int price;
           Laptop(int p) {
                price = p;
           }
           int showPrice() {
                return price;
           }
     }

     public static void main(String args[]) {

           System.out.println("Laptops :");

           for(Laptop lap : Laptop.values()) {
                System.out.println("Ordinal value of "+lap.name()+
                           " is "+lap.ordinal());
           }
           System.out.println("HP index "+ Laptop.HP.ordinal());
     }
}

Output:
     Laptops :
     Ordinal value of Dell is 0
     Ordinal value of HP is 1
     Ordinal value of Lenovo is 2
     HP index 1

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...