DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How To Perform OCR on a Photograph of a Receipt Using Java
  • How to Convert Files to Thumbnail Images in Java
  • The Pitfalls of Using Boolean Parameters in Methods: A Java Tutorial
  • The Long Road to Java Virtual Threads

Trending

  • AI Coding Agent Guardrails: Finding Gaps in Tool Permissions
  • When One Docker Swarm Replica Became Unreachable Over an Overlay Network: A Production Case With Traefik
  • Event-Driven AI Systems With Kafka and Autonomous Agents
  • Claude Code Superpowers: The 5-Tool Stack That Ends Limits and Context Amnesia

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Data
  4. Enum: Using the Name() and toString() Methods Correctly

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.

By 
Alex Theedom
·
Sep. 21, 17 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
222.9K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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.

unit test Listing (computer) Strings Data Types Java (programming language) Release (computing) Documentation Document Correctness (computer science)

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

Opinions expressed by DZone contributors are their own.

Related

  • How To Perform OCR on a Photograph of a Receipt Using Java
  • How to Convert Files to Thumbnail Images in Java
  • The Pitfalls of Using Boolean Parameters in Methods: A Java Tutorial
  • The Long Road to Java Virtual Threads

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook