Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Enum: Using the Name() and toString() Methods Correctly

DZone's Guide to

Enum: Using the Name() and toString() Methods Correctly

With Java Enums, there are two similar, but different methods that are commonly used: name() and toString(). Learn the difference and when to use both for best results.

· Java Zone
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

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 it cannot be overwritten. Meanwhile, 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 exactly match 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. That's useful, for example, 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.

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:
enum ,java ,tostring ,name method ,tutorial

Published at DZone with permission of Alex Theedom, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}