toString() method returns the name of this enum constant, as contained in the declaration.
The Java Enum has two methods that retrieve that value of an enum constant, name() and toString().
The name() method of Enum class returns the name of this enum constant same as declared in its enum declaration. The toString() method is mostly used by programmers as it might return a more easy to use name as compared to the name() method.
Description. The java.lang.Enum.name() method returns the name of this enum constant, exactly as declared in its enum declaration.
The main difference between name()
and toString()
is that name()
is a final
method, so it cannot be overridden. The toString()
method returns the same value that name()
does by default, but toString()
can be overridden by subclasses of Enum.
Therefore, if you need the name of the field itself, use name()
. If you need a string representation of the value of the field, use toString()
.
For instance:
public enum WeekDay {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY;
public String toString() {
return name().charAt(0) + name().substring(1).toLowerCase();
}
}
In this example,
WeekDay.MONDAY.name()
returns "MONDAY", and
WeekDay.MONDAY.toString()
returns "Monday".
WeekDay.valueOf(WeekDay.MONDAY.name())
returns WeekDay.MONDAY
, but WeekDay.valueOf(WeekDay.MONDAY.toString())
throws an IllegalArgumentException
.
Use toString() when you want to present information to a user (including a developer looking at a log). Never rely in your code on toString()
giving a specific value. Never test it against a specific string. If your code breaks when someone correctly changes the toString()
return, then it was already broken.
If you need to get the exact name used to declare the enum constant, you should use name() as toString
may have been overridden.
Use toString
when you need to display the name to the user.
Use name
when you need the name for your program itself, e.g. to identify and differentiate between different enum values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With