Convert enum to String

suggest change

Sometimes you want to convert your enum to a String, there are two ways to do that.

Assume we have:

public enum Fruit {
    APPLE, ORANGE, STRAWBERRY, BANANA, LEMON, GRAPE_FRUIT;
}

So how do we convert something like Fruit.APPLE to "APPLE"?

Convert using name()

name() is an internal method in enum that returns the String representation of the enum, the return String represents exactly how the enum value was defined.

For example:

System.out.println(Fruit.BANANA.name());      // "BANANA"
System.out.println(Fruit.GRAPE_FRUIT.name()); // "GRAPE_FRUIT"

Convert using toString()

toString() is, by default, overridden to have the same behavior as name()

However, toString() is likely overridden by developers to make it print a more user friendly String

Don’t use toString() if you want to do checking in your code, name() is much more stable for that. Only use toString() when you are going to output the value to logs or stdout or something

By default:

System.out.println(Fruit.BANANA.toString());      // "BANANA"
System.out.println(Fruit.GRAPE_FRUIT.toString()); // "GRAPE_FRUIT"

Example of being overridden

System.out.println(Fruit.BANANA.toString());      // "Banana"
System.out.println(Fruit.GRAPE_FRUIT.toString()); // "Grape Fruit"

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Enums:
* Enums
* Convert enum to String

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap