Enum.ordinal() Method in Java

 

Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero). For example, let's have weekdays in an enum starting from Monday, Tuesday till Sunday. So the ordinal of Monday will be 0, Tuesday will be 1, etc.,

Enum.ordinal() Method in Java


Let's see simple Java for the same.


enum Days{
// 0 1  2     3         4       5  6 
 MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}

public class EnumOrdinal {
 public static void main(String[] args) {
  Days mon = Days.MONDAY;
  Days wed = Days.WEDNESDAY;
  Days tus = Days.TUESDAY;
  Days fri = Days.FRIDAY;
  Days sun = Days.SUNDAY;
  
  System.out.println("Monday ordinal    : "+mon.ordinal());
  System.out.println("Wednesday ordinal : "+wed.ordinal());
  System.out.println("Tuesday ordinal   : "+tus.ordinal());
  System.out.println("Friday ordinal    : "+fri.ordinal());
  System.out.println("Sunday ordinal    : "+sun.ordinal());
 }
}


OUTPUT:


Monday ordinal    : 0
Wednesday ordinal : 2
Tuesday ordinal   : 1
Friday ordinal    : 4
Sunday ordinal    : 6

No comments:
Write comments