1
public enum Style {
    BIG,MEDIUM,SMALL;
    
    public static void main(String[] args) {
        System.out.println(Style.SMALL.toString() == "SMALL");
    }
  
}

Why does this work? I expect the print to be false, since == compares the object references. However, it prints true.

I would appreciate if someone can explain the underlying behaviour.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Danny Julian
  • 77
  • 1
  • 1
  • 6
  • 3
    I don't think this behaviour is actually specified. The docs for [`Enum.toString`](https://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html#toString--) doesn't say that the returned string will be an interned one, so depending on the implementation, I think this could give you `false`. – Sweeper Sep 03 '21 at 00:50
  • Interesting, this has been like this for years on a project im working on, and its been running bug free. – Danny Julian Sep 03 '21 at 00:53
  • 1
    Related: https://stackoverflow.com/q/27908213/5754656 (Since `Enum#toString()` just calls `Enum#name()`) – Artyer Sep 03 '21 at 00:55
  • but remember that small strings are heaped, so it would still end up being true on any proper jvm – Mike 'Pomax' Kamermans Sep 03 '21 at 00:56
  • 4
    The real answer is: It’s not surprising that this works, but you cannot safely assume it will always work. – VGR Sep 03 '21 at 01:02

0 Answers0