Close

Java - How to find enum by ordinal?

[Last Updated: Sep 23, 2020]

Java Enum 

Following example shows how to get Java Enum element by its ordinal (index).

package com.logicbig.examle;

import java.time.temporal.ChronoUnit;

public class GetEnumByOrdinal {
  public static void main(String[] args) {
      ChronoUnit unit = ChronoUnit.values()[2];
      System.out.println(unit);
  }
}
Millis

A user defined enum:

package com.logicbig.examle;

public class GetEnumByOrdinal2 {

  enum WeekEnd{
      Saturday,
      Sunday
  }

  public static void main(String[] args) {
      WeekEnd weekEnd = WeekEnd.values()[0];
      System.out.println(weekEnd);

      weekEnd = WeekEnd.values()[1];
      System.out.println(weekEnd);

  }
}
Saturday
Sunday

See Also