Java enum tostring vs name

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

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.

Читайте также:  What is php soap extension

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

Источник

Digital Transformation and Java Video Training

Java | Integration | MuleSoft | Digital Transformation | API-led connectivity | RESTful API

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

Posted on September 19, 2017 by Alex in Enum, Java 6, Java 7, Java 8 // 0 Comments

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.

Источник

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

Join the DZone community and get the full member experience.

Читайте также:  Python debugging in sublime text

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

unit test Listing (computer) Strings Data Types Java (programming language) Release (agency) 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.

Источник

Enum to String in Java

Enum to String in Java

  1. Convert Enum to String Using name() in Java
  2. Convert Enum to String Using toString() in Java

Enum in Java is a special data type or class that holds a set of constants. We can add constructors and methods in an enum, too. To create an enum in Java, we use the keyword enum and give it a name just like a class. In this article, we will go through the ways to convert an enum to string Java.

Читайте также:  Html button onclick class

Convert Enum to String Using name() in Java

In the first example, we will use name() of the Enum class to return the enum constant’s exact name as a string. Below, we have created an enum inside the class, but we can create an enum either outside or inside it. We named the enum Directions , which contains the names of directions as enum constant.

We can fetch any constant using the name() method. Directions.WEST.name() will return WEST as a string, which is stored in the string variable getWestInString and then print in the output.

public class EnumToString   enum Directions   NORTH,  SOUTH,  EAST,  WEST  >   public static void main(String[] args)   String getWestInString = Directions.WEST.name();  System.out.println(getWestInString);  > > 

Convert Enum to String Using toString() in Java

Just like name() we have the toString() method, but when it comes to using an enum constant for any important purpose, name() is preferred because it returns the same constant while toString() can be overridden inside the enum. It means that we can modify what is returned as a string using toString() , which we will see in the next example.

In this example, we use the toString() method on the constant that needs to be converted to a string.

public class EnumToString    enum Currencies   USD,  YEN,  EUR,  INR  >   public static void main(String[] args)   String getCurrency = Currencies.USD.toString();  System.out.println(getCurrency);  > > 

We have discussed above that we can override the toString() method to modify what we want to return as a string with the enum constant. In the example below, we have four currencies as constants calling the enum constructors with a string passed as an argument.

Whenever a constant sees a toString() method, it will pass the string name to getCurrencyName , a string variable. Now we have to override the toString() method inside the enum and return the getCurrencyName with a string.

In the main() method, we used toString() to get the INR constant as string. We can see in the output that the modified string is printed. We can also print all the values of an enum using Enum.values() , which returns an array of enum constants and then loop through every constant to print them as strings.

public class EnumToString    enum Currencies   USD("USD"),  YEN("YEN"),  EUR("EUR"),  INR("INR");   private final String getCurrencyName;   Currencies(String currencyName)   getCurrencyName = currencyName;  >   @Override  public String toString()   return "Currency: " + getCurrencyName;  >  >   public static void main(String[] args)   String getCurrency = Currencies.INR.toString();  System.out.println("Your " + getCurrency);   Currencies[] allCurrencies = Currencies.values();  for (Currencies currencies : allCurrencies)   System.out.println("All " + currencies);  >  > > 
Your Currency: INR All Currency: USD All Currency: YEN All Currency: EUR All Currency: INR 

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

Related Article — Java String

Related Article — Java Enum

Copyright © 2023. All right reserved

Источник

Оцените статью