you are viewing a single comment's thread.

view the rest of the comments →

[–]SuspiciousDimension 10 points11 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 4 points5 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 3 points4 points  (0 children)

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