Shawn Elledge Shawn Elledge - 1 month ago 11
Java Question

Doesn't the default Object.toString() append hashCode()?

I have an Enum class in Airport.java

package test;

public enum Airport {
PHX,
LAX,
SFO,
NRT,
SIN;

Airport() {
}
}


and a Test class in Test.java

package test;

public class Test {

public static void main(String[] args) {
Airport a = Airport.PHX;
System.out.println(a);
System.out.println(String.valueOf(a));
System.out.println(a.name());
System.out.println(a.toString());
System.out.println(a.name() + '@' + Integer.toHexString(a.hashCode()));
}

}


The output for this is

PHX
PHX
PHX
PHX
PHX@15db9742


but shouldn't the output be

PHX
PHX
PHX
PHX@15db9742
PHX@15db9742


According the the Object API https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html the default
Object.toString()
is
getClass().getName() + '@' + Integer.toHexString(hashCode())

Answer

That's indeed the default implementation of toString(). However, java.lang.Enum, the implicit base class for all enums overrides toString() by returning its name.

Comments