Course contentsShow
← Java
Lesson 608 of 2,87014. EnumerationsFree lesson

The name() Method: Getting the Enum Constant's Identifier

Learn how name() returns the exact identifier of the enum constant as declared in source code.

The name() Method: Getting the Enum Constant's Identifier

You'll learn how to retrieve the exact source code identifier of an enum constant using the name() method.

What Is the name() Method?

Every enum constant in Java has a built-in name() method that returns a String containing the exact identifier you declared in your source code. Unlike toString() (which can be overridden), name() always returns the literal constant name as you typed it.

How It Works

When you declare an enum like Status { PENDING, APPROVED, REJECTED }, each constant has an identifier. The name() method returns that identifier as a string:

public enum Status {
    PENDING, APPROVED, REJECTED
}

Status current = Status.APPROVED;
String identifier = current.name(); // Returns "APPROVED"

Think of name() as asking "What is this constant called in the source code?" The answer is always the uppercase identifier exactly as you wrote it.

name() vs toString()

While toString() can be overridden to return custom strings, name() is final and cannot be changed. It's the guaranteed, unchangeable identifier:

public enum Priority {
    HIGH, MEDIUM, LOW;
    
    @Override
    public String toString() {
        return "Priority: " + name(); // Can customize toString
    }
}

Priority p = Priority.HIGH;
System.out.println(p.name());     // Always "HIGH"
System.out.println(p.toString()); // "Priority: HIGH"

When to Use name()

Use name() when you need the exact source code identifier—for example, when serializing to formats that require precise constant names, or when debugging to see the raw identifier.

Key Takeaway: The name() method returns the exact, unchangeable identifier of an enum constant as declared in source code, providing a reliable way to retrieve the constant's original name.