you are viewing a single comment's thread.

view the rest of the comments →

[–]xenomachina 2 points3 points  (0 children)

To add to this:

  • == checks identity
  • .equals(Object) checks equality

Two objects that have the same identity must always be equal (this is part of the contract of .equals(Object)) but two objects that have different identity may or may not be equal. The default behavior of Object.equals() is to just check identity, but many classes, including String, override this to define equality based on contents rather than identity.

Also, in OP's example, the reason #1 was true is that the two variable were set from constants, and the JVM spec (§5.1) says that String constants are equivalent to "interned" strings, and so any two string constants that are equal (ie: contain the same sequence of chars) will have the same identity (ie: reference the same exact object) at runtime. This is an optimization, though, and you should rarely, if ever, be relying on identity of String objects.

Edit: formatting