Core Java

Enum: How to use name() and toString() methods correctly

The Difference Between Two Methods?

The Java Enum has two methods that retrieve that value of an enum constant, name() and .toString(). The toString() method calls the name() method which returns the string representation of the enum constant. In listing 1, the value returned by calling the name() and toString() on an Animal.DOG constant method is DOG.

Listing 1: Animal Enum

public enum Animal {
    DOG
}

// Unit test
assertThat(DOG.toString()).isEqualTo(DOG.name());

So given that both methods return the same value you might think that they can be used interchangeably, and in the majority of cases this would be true. However, the difference between these two methods is important.

What’s the Difference?

The name() method is final, so cannot be overwritten while conversely, the toString() method is open and can be overwritten. In fact, overwriting the toString() method is encouraged. It should be implemented and return a friendly version of the enum constant. Listing 2 shows how this might be done.

Listing 2: Overwrite the toString() method

public enum Animal {
    DOG {
        public String toString() {
            return "Dog";
        }
    }
}

// Unit test
assertThat(DOG.toString()).isNotEqualTo(DOG.name());

The output of calling toString() on the Animal.DOG enum constant is Dog. So now the name() method and the toString() method do not return the same value.

What the Java Documents Say

Let’s dive a little deeper and look at the Java Documentation, which advises that:

Most programmers should use the toString() method in preference to the name() method, as the toString() method may return a more user-friendly name.

This raises the question. When should we use the .name() method?

According to the Java Documentation:

The name() 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.

So what specialized situations are they referring to? The valueOf() method might give us a hint. This method takes a String value and attempts to find the enum that matches it exactly. Take a look at the code in listing 3.

Listing 3: The valueOf() method returns DOG

assertThat(DOG).isEqualTo(Animal.valueOf("DOG"));

The String value passed to the valueOf() method must match exactly to the enum constant, otherwise, an IllegalArgumentException is thrown.

Source Code

The code examples and unit tests for this article are stored in the GitHub repository ReadLearnCode/readlearncode_articles.

Conclusion

This is a very useful method when populating an enum field based on a string value. An example of when this might do this is when deserializing a JSON document that contains an enum constant. In this case, the name() method should be used in order to preserve round-trip equivalence.

You cannot guarantee that the toString() method would not be overwritten but the name() method will always return the string equivalence of the enum.

Further Reading

You might be interested in my article An Enum implementation of the Strategy Pattern.

Published on Java Code Geeks with permission by Alex Theedom, partner at our JCG program. See the original article here: Enum: How to use name() and toString() methods correctly

Opinions expressed by Java Code Geeks contributors are their own.

Alex Theedom

Alex Theedom is a Senior Java Developer and has recently played a pivotal role in the architectural design and development of a microservice based, custom built lottery and instant win game platform. Alex has experience of Java web application development in a diverse range of fields including finance, e-learning, lottery and software development. He is the co-author of Professional Java EE Design Patterns and many articles.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button