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

name() vs toString(): When to Override toString()

Compare name() and toString() methods and learn best practices for custom enum string representations.

name() vs toString(): When to Override toString()

What you'll learn: You'll discover the difference between an enum's name() and toString() methods, and when customizing toString() improves your code's readability.

Understanding the Two Methods

Every enum constant has both a name() and a toString() method. By default, they return the exact same value: the identifier you declared in your enum.

enum Priority {
    LOW, MEDIUM, HIGH
}

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

The Key Difference

name() is final — you cannot override it. It always returns the exact identifier as declared in code. This makes it reliable for internal logic like serialization or data storage.

toString() can be overridden to provide a more human-friendly representation for display purposes, debugging, and logging.

When to Override toString()

Think of name() as the "official ID" and toString() as the "display label." Override toString() when you want user-friendly output:

enum Status {
    IN_PROGRESS, COMPLETED, NOT_STARTED;
    
    @Override
    public String toString() {
        return name().toLowerCase().replace('_', ' ');
    }
}

Status s = Status.IN_PROGRESS;
System.out.println(s.name());     // "IN_PROGRESS"
System.out.println(s.toString()); // "in progress"

Best Practice

  • Use name() for persistence, parsing, and internal logic where stability matters
  • Override toString() for human-readable output in logs, UIs, and error messages
  • Never rely on toString() for program logic — someone might change it

Key Takeaway: name() is your enum's unchangeable identifier, while toString() is the customizable display format — override toString() when you need prettier output, but always use name() for reliable programmatic operations.