News Ticker

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

enum

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.

Leave a Reply

%d bloggers like this: