Platformhard8+ years

`a` is the literal "code". Which of `"co" + "de"`, `fco + "de"` (with `final String fco = "co"`), `nco + "de"` (without `final`), `new StringBuilder("co").append("de").toString()` and `new String("code")` are `==` to `a`? What does `intern()` change, and what does it not?

Only the two constant expressions: "co" + "de" and fco + "de" with a final constant fco. javac folds them into the literal "code" at compile time (JLS §15.29), so they are the pooled object. Dropping final from fco turns the same line into a runtime concatenation, a new object, and == is false; the builder and new String are new objects too. intern() returns the pooled instance for that text, so c.intern() == a is true, but c itself is unchanged and c == a stays false: it returns a reference, it does not move an object into the pool.

The lesson behind it →
More on Platform