Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

java.lang.Enum — string representations of constants

java.lang.Enum is the base class of enumeration types. Learn how the overridable toString() method differs from name(), which returns a constant's exact declared name.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

public abstract class Enum<E extends Enum<E>>
public String toString()
public final String name()

java.lang.Enum is the common base class of types declared using enum. An enumeration type defines named constants such as State.READY.

Enum.toString() returns the constant's declared name by default. You can override it to provide more readable text. In contrast, name() is final and always returns the constant's exact declared name.

State.valueOf("READY") looks up a constant by its exact name, not its toString() result. Matching is case-sensitive; State.valueOf("Ready") throws IllegalArgumentException. Therefore, do not treat a display label as the name used to retrieve a constant.

Examples

public class Main {
    enum State {
        READY;

        @Override
        public String toString() {
            return "Ready";
        }
    }

    public static void main(String[] args) {
        System.out.println(State.READY.toString());
        System.out.println(State.READY.name());
        System.out.println(State.valueOf("READY") == State.READY);
    }
}

Result

Ready
READY
true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources