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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

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

  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 1
  • Power BI Embedded Analytics — Part 2: Power BI Embedded Overview
  • Java Virtual Threads and Scaling
  • Performance Optimization Techniques for Snowflake on AWS
  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 user avatar
Alex Theedom
·
Sep. 21, 17 · Tutorial
Likes (12)
Comment
Save
Tweet
Share
219.6K Views

Join the DZone community and get the full member experience.

Join For Free

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, DZone MVB. 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
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!