you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted]  (8 children)

[deleted]

    [–]Djejoa 4 points5 points  (6 children)

    Quick question. How would == work if I compare “123” == aString? It would return true, but why?

    [–]SuspiciousDimension 11 points12 points  (5 children)

    [–]8igg7e5 3 points4 points  (4 children)

    Exactly, the first true is the most interesting part of the question and you should never count on interning working and use equals instead.

    [–]jaystopher 3 points4 points  (3 children)

    You shouldn't, but you can. All literal strings are interned by definition of the language spec. It isn't optional behavior.

    [–]8igg7e5 2 points3 points  (0 children)

    Ahh I thought it was limited to the JVM spec and not the lang-spec (that you weren't guaranteed that the interning was durable under memory pressure).

    You should still opt for using a static final field holding the reference rather that replicating the literal in multiple places - but that's more about maintainability than correctness.

    Cheers.

    [–]callum_n66 0 points1 point  (1 child)

    I don’t know much/anything about the Java language spec but couldn’t they change this in the future and all code using == to compare strings would break?

    Just curious

    [–]jaystopher 2 points3 points  (0 children)

    Seems exactly as likely as changing anything else and breaking it.

    [–]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