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 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"
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents