Are enum names interned in Java?

Although there is no explicit guarantee of this, the end result is bound to be such that the comparison always succeeds for enum constants with identical names:

enum A {enum1};
enum B {enum1};
System.out.println(A.enum1.name() == B.enum1.name()); // Prints "true"

The reason for this is that Java compiler constructs subclasses of Enum in such a way that they end up calling Enum‘s sole protected constructor, passing it the name of enum value:

protected Enum(String name, int ordinal);

The name is embedded into the generated code in the form of a string literal. According to String documentation,

All literal strings and string-valued constant expressions are interned.

This amounts to an implicit guarantee of your expression succeeding when names of enum constants are identical. However, I would not rely on this behavior, and use equals(...) instead, because anyone reading my code would be scratching his head, thinking that I made a mistake.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)