Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

If you look in the enum api at the method name() it says that:

Returns the name of this enum constant, exactly as declared in its enum declaration. Most programmers should use the toString method in preference to this one, as the toString method may return a more user-friendly name. This method is designed primarily for use in specialized situations where correctness depends on getting the exact name, which will not vary from release to release.

Why is better to use toString()? I mean toString may be overridden when name() is already final. So if you use toString and someone overrides it to return a hard-coded value your whole application is down... Also if you look in the sources the toString() method returns exactly and just the name. It's the same thing.

1 Answer

0 votes
by (46k points)

t really depends on what you want to do with the returned value:

  • If you need to get the exact name used to declare the enum constant, you should use name() as toString may have been overriden
  • If you want to print the enum constant in a user friendly way, you should use toString which may have been overriden (or not!).

When I feel that it might be confusing, I provide a more specific getXXX method, for example:

public enum Fields {

    LAST_NAME("Last Name"), FIRST_NAME("First Name");

    private final String fieldDescription;

    private Fields(String value) {

        fieldDescription = value;

    }

    public String getFieldDescription() {

        return fieldDescription;

    }

}

Browse Categories

...