Java - Enum Constants Reverse Lookup

Introduction

You can get an enum constant via its name or position in the list.

This is also called as reverse lookup based on the name or ordinal of an enum constant.

valueOf() method added by the compiler to an enum type performs reverse lookup based on a name.

values() added by the compiler to an enum type performs reverse lookup by ordinal.

The order of the values returned by values() method is the same as the order in which the enum constants are declared.

The ordinal of enum constants starts at zero.

The following code demonstrates how to reverse look up enum constants:

Demo

enum Level {
  LOW, MEDIUM, HIGH, URGENT;//from w  w w.ja  va  2s . co  m
}

public class Main {
  public static void main(String... args) {
    Level low1 = Level.valueOf("LOW"); // A reverse lookup using a name
    Level low2 = Level.values()[0]; // A reverse lookup using an ordinal
    System.out.println(low1);
    System.out.println(low2);
    System.out.println(low1 == low2);
  }
}

Result

Quiz