Java 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).
Syntax
public final int ordinal()
Parameters
No parameter is required.
Return Value
Returns the ordinal of this enumeration constant.
Exception
NA.
Example:
In the example below, the java.lang.Enum.ordinal() method returns the ordinal of the given enumeration constant.
import java.lang.*; public class MyClass { //creating an enum public enum WeekDay{ MON("1st"), TUE("2nd"), WED("3rd"), THU("4th"), FRI("5th"); String day; WeekDay(String x) { day = x; } String showDay() { return day; } } public static void main(String[] args) { for(WeekDay i : WeekDay.values()) { System.out.println("ordinal for " + i + " is " + i.ordinal()); System.out.println(i + " is the " + i.showDay() + " day of the week."); } } }
The output of the above code will be:
ordinal for MON is 0 MON is the 1st day of the week. ordinal for TUE is 1 TUE is the 2nd day of the week. ordinal for WED is 2 WED is the 3rd day of the week. ordinal for THU is 3 THU is the 4th day of the week. ordinal for FRI is 4 FRI is the 5th day of the week.
❮ Java.lang - Enum