Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Enum.values()

Methods of every enum: values() gives all constants, valueOf() finds one by name, ordinal() and name() give its index and name.

Available since: Java 5

Syntax

public static E[] values()

Return value

E[]A new array with all constants in declaration order.

Examples

Iterating over constants with their index and name:

enum Size { SMALL, MEDIUM, LARGE }
 
void main() {
    for (Size s : Size.values()) {
        IO.println(s.ordinal() + " " + s.name());
    }
    IO.println(Size.values().length);
}

Output:

0 SMALL
1 MEDIUM
2 LARGE
3

valueOf() turns a string into a constant; the name must match exactly, including case:

enum Size { SMALL, MEDIUM, LARGE }
 
void main() {
    Size s = Size.valueOf("MEDIUM");
    IO.println(s == Size.MEDIUM);
    IO.println(Size.valueOf("large".toUpperCase()));
}

Output:

true
LARGE

An unknown name throws an exception:

enum Size { SMALL, MEDIUM, LARGE }
 
void main() {
    Size.valueOf("HUGE");
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: No enum constant Main.Size.HUGE

Notes

The compiler adds values() and valueOf() to every enum. values() creates a new array each time — in a hot loop keep it in a variable. ordinal() depends on declaration order, so do not store it in a database: adding a constant in the middle shifts every number. name() always returns the name from the code, while toString() can be overridden.

See also

  • enum — Declares an enum — a type with a fixed set of values.
  • EnumMap — A map whose keys are values of one enum. Fast, and keeps keys in declaration order.
  • EnumSet — A set of values of one enum. Works like a set of bit flags, but with readable code.
  • IllegalArgumentException — Signals that a method received an invalid argument.

Related recipes

In the tutorial

  • Enums — Enums in Java: a fixed set of values, values() and valueOf(), switch over an enum, fields and methods.

Thanks for reading!

Donate to the site — we work hard for you.