Convert enum to String
suggest changeSometimes 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 a final method of Enum. It returns the declared name of the constant, exactly as it appears in source.
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 often overridden to return 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
The Fruit enum above does not override toString, so it still prints the declared names. If a constant's toString is overridden to return a display name, the output can look like this:
System.out.println(Fruit.BANANA.toString()); // "Banana"
System.out.println(Fruit.GRAPE_FRUIT.toString()); // "Grape Fruit"