Java enum - why use toString instead of name
name()
is a "built-in" method of enum
. It is final and you cannot change its implementation. It returns the name of enum constant as it is written, e.g. in upper case, without spaces etc.
Compare MOBILE_PHONE_NUMBER
and Mobile phone number
. Which version is more readable? I believe the second one. This is the difference: name()
always returns MOBILE_PHONE_NUMBER
, toString()
may be overriden to return Mobile phone number
.
Use name()
when you want to make a comparison or use the hardcoded value for some internal use in your code.
Use toString()
when you want to present information to a user (including a developper 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.
From the javadoc (emphasis mine) :
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
It really depends on what you want to do with the returned value:
- If you need to get the exact name used to declare the enum constant, you should use
name()
astoString
may have been overriden - If you want to print the enum constant in a user friendly way, you should use
toString
which may have been overriden (or not!).
When I feel that it might be confusing, I provide a more specific getXXX
method, for example:
public enum Fields {
LAST_NAME("Last Name"), FIRST_NAME("First Name");
private final String fieldDescription;
private Fields(String value) {
fieldDescription = value;
}
public String getFieldDescription() {
return fieldDescription;
}
}