If pool memory already has an object with similar content, then if we try to create the same object with different reference variable then only a new reference variable is created, NO NEW OBJECT IS CREATED.eg;
That is actually not true in the general case. What you are describing is called String interning
. An interned
String will always be reference-equal to any other interned String with the same content - that's basically the guarantee of intern
. (From the docs on String.intern
: It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.). If I were to create 2 Strings from a constant byte array, then even as they share the content, those will be different objects.
The JLS further specifies that:
Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.
Hence why you get equality of String literals, and anything that is a value of [a] constant expression.
So, what is this constant expression? Well, again, according to the JLS, those are literals, Simple names (§6.5.6.1) that refer to constant variables, various non-String stuffs, and expressions with +
, but only as long as both operands of +
are themselves constant expressions
(The String object is newly created (§12.5) unless the expression is a constant expression (§15.28).). So this means that, unless your Strings on both sides of +
are literals, final strings with the value being a constant expression or fulfill one of the other conditions (like a cast from a primitive constant), a new object will be created.