Skip to lesson

Built-in enum methods: values(), name(), valueOf(), ordinal()

Every enum gets four methods for free: values() lists all its constants, name() gives a constant's name as text, valueOf() turns text back into a constant, and ordinal() gives a constant's position.

values(): every constant, in order

values() is a static method that Java adds to every enum. It returns a new array holding all the enum's constants, in the order they are declared.

A booking screen must list every payment mode, and the list should grow by itself when a mode is added. Loop over values() instead of typing each constant.

Example 1 · A payment menu built from values()

PaymentMenuDemo.javaJava
enum PaymentMode {    UPI, DEBIT_CARD, CREDIT_CARD, NET_BANKING, CASH_ON_DELIVERY}
public class PaymentMenuDemo {    public static void main(String[] args) {        PaymentMode[] modes = PaymentMode.values();        System.out.println("Choose a payment mode (" + modes.length + " options):");        int number = 1;        for (PaymentMode m : modes) {            System.out.println(number + ". " + m);            number++;        }    }}
Output
Choose a payment mode (5 options):
1. UPI
2. DEBIT_CARD
3. CREDIT_CARD
4. NET_BANKING
5. CASH_ON_DELIVERY

What this code does

  • values() is called on the enum name, because it is static. It returns a PaymentMode[], so modes.length is the number of constants.
  • The for-each loop visits the constants in declaration order. Add WALLET to the enum, and the menu shows six options without any other change.

Each call returns a new array. Changing that array, such as all[0] = PaymentMode.CARD, never changes the enum itself. You will not find values() in the java.lang.Enum documentation: the compiler writes it into every enum, because only the compiler knows that enum's constants.

name(): the constant's exact name

name() returns the name of an enum constant as a String, exactly as it is written in the enum, such as "AC_3_TIER". The method is final, so no enum can change what it returns.

A ticket app must save the chosen class in a file as text. name() gives that text, the same text that printing the constant shows.

Example 2 · name(): save and show a constant as text

NameDemo.javaJava
enum TrainClass {    SLEEPER, AC_3_TIER, AC_2_TIER, AC_FIRST}
public class NameDemo {    public static void main(String[] args) {        TrainClass booked = TrainClass.AC_3_TIER;        String saved = booked.name();        System.out.println("Saved: " + saved);        System.out.println("Letters: " + saved.length());        System.out.println("Shown: " + saved.replace('_', ' '));        System.out.println("Is it sleeper? " + saved.equals("SLEEPER"));    }}
Output
Saved: AC_3_TIER
Letters: 9
Shown: AC 3 TIER
Is it sleeper? false

What this code does

  • booked.name() is a normal String, so every String method works on it: length(), replace(), equals().
  • The text is exactly the declared name, underscores and capitals included. That makes it safe to save and to read back later.

Printing a constant calls its toString() method, which returns the same name by default. An enum may override toString() to show a friendlier label (toString() (opens in a new tab) covers it), but name() never changes. So save and compare with name(), and show labels with toString() or your own method.

valueOf(): from text back to a constant

valueOf(String) is a static method that Java adds to every enum. It returns the constant whose name matches the text exactly, and throws IllegalArgumentException when no constant has that name.

A saved file says "AC_2_TIER", and a user types sleeper in a form. valueOf() turns such text into a constant, but only when it matches a name exactly, capitals included.

Example 3 · valueOf() returns the existing constant

ValueOfDemo.javaJava
enum TrainClass {    SLEEPER, AC_3_TIER, AC_2_TIER, AC_FIRST}
public class ValueOfDemo {    public static void main(String[] args) {        String fromFile = "AC_2_TIER";        TrainClass t = TrainClass.valueOf(fromFile);        System.out.println("Loaded: " + t);        System.out.println(t == TrainClass.AC_2_TIER);    }}
Output
Loaded: AC_2_TIER
true

What this code does

  • valueOf("AC_2_TIER") finds the constant with exactly that name.
  • It hands back the one existing AC_2_TIER object, not a copy, so == is true.

Example 4 · Mistake: valueOf() with text that does not match

ValueOfCrashDemo.javaJava
enum TrainClass {    SLEEPER, AC_3_TIER, AC_2_TIER, AC_FIRST}
public class ValueOfCrashDemo {    public static void main(String[] args) {        String typed = "sleeper";        System.out.println("You typed: " + typed);        TrainClass t = TrainClass.valueOf(typed);        System.out.println("Booking " + t);    }}
Sample output
You typed: sleeper
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant TrainClass.sleeper
	at java.base/java.lang.Enum.valueOf(Enum.java:274)
	at TrainClass.valueOf(ValueOfCrashDemo.java:1)
	at ValueOfCrashDemo.main(ValueOfCrashDemo.java:9)

What this code does

  • valueOf is case-sensitive: "sleeper" is not SLEEPER. The message No enum constant TrainClass.sleeper names the text it could not find.
  • Skip the java.base/... line (its number depends on your Java version). The last line points to line 9, the valueOf call.

Example 5 · Fix: clean the text and catch bad input

SafeValueOfDemo.javaJava
enum TrainClass {    SLEEPER, AC_3_TIER, AC_2_TIER, AC_FIRST}
public class SafeValueOfDemo {    static TrainClass parse(String text) {        try {            return TrainClass.valueOf(text.trim().toUpperCase());        } catch (IllegalArgumentException e) {            System.out.println("Not a class: " + e.getMessage());            return null;        }    }
    public static void main(String[] args) {        String[] inputs = { "sleeper", " ac_3_tier ", "AC3" };        for (String in : inputs) {            TrainClass t = parse(in);            if (t != null) {                System.out.println("Booked: " + t);            }        }    }}
Output
Booked: SLEEPER
Booked: AC_3_TIER
Not a class: No enum constant TrainClass.AC3

What this code does

  • trim() removes the spaces and toUpperCase() fixes the case, so " ac_3_tier " becomes AC_3_TIER before valueOf sees it.
  • "AC3" is still not a constant name. The catch block handles it, so the program keeps running.

valueOf(null) throws NullPointerException instead. For text from a user, clean it with trim() and toUpperCase(), and catch the exception, as in Validating input with exceptions (opens in a new tab).

ordinal(): the position, and why not to save it

ordinal() returns the position of an enum constant in its declaration, counting from 0. It changes whenever constants are added, removed or reordered, so it must never be saved.

SLEEPER is declared first, so its ordinal is 0. If a new class is later added before AC_3_TIER, every number after it moves up by one.

Before: SLEEPER 0, AC_3_TIER 1, AC_2_TIER 2. A booking saved the number 1 for AC_3_TIER. After AC_ECONOMY is added between SLEEPER and AC_3_TIER, ordinal 1 is AC_ECONOMY, so the saved 1 now reads as the wrong class. The saved name "AC_3_TIER" still finds the right one.

Example 6 · ordinal() for each constant, name() for saving

OrdinalDemo.javaJava
enum TrainClass {    SLEEPER, AC_3_TIER, AC_2_TIER, AC_FIRST}
public class OrdinalDemo {    public static void main(String[] args) {        for (TrainClass t : TrainClass.values()) {            System.out.println(t.ordinal() + " " + t);        }        TrainClass booked = TrainClass.AC_3_TIER;        String saved = booked.name();        TrainClass loaded = TrainClass.valueOf(saved);        System.out.println("Saved " + saved + ", loaded " + loaded);    }}
Output
0 SLEEPER
1 AC_3_TIER
2 AC_2_TIER
3 AC_FIRST
Saved AC_3_TIER, loaded AC_3_TIER

What this code does

  • Ordinals count from 0 in declaration order. They are today's positions, not fixed codes.
  • The booking is saved as the name AC_3_TIER and read back with valueOf(). That keeps working even after new classes are added in between.

A number saved in a file or database before the change now points to a different constant, and no error appears anywhere. To save an enum value, save name() and read it back with valueOf(). Using ordinal() while the program runs, for example as an array index for counting, is fine.

Next step

Check your understanding

12 quick questions