But now, the 2 Strings are not equals at the first time. Then I try to create a new String (s2) equals to the first (follow me??),
String s1 = "abc"; String s2 = "abc"; if (s1 == s2) System.out.println("String s1 == s2"); // The message is displayed
String s1 = "abc"; String s2 = "ab"; s2 = s2 + "c"; if (s1 == s2) System.out.println("String s1 == s2"); // The 2 references are different
Am I clear? Or am I completely wrong with the mechanism of the "String Constant Pool"??
s1 ----+-----> "abc" | | s2 ----+--X--> "ab"
So, when 2 Strings have the same value, there is only one constant in the poolIf they are compile-time literals, or have been interned. Otherwise they may not be equal to the constant in the pool; String foo = String.valueOf(7) is not guarenteed to create a pool constant.
Schematically: s1 ----+-----> "abc"I don't have a clue what the X and the vertical line in that diagram is supposed to represent, but AFAIK there's no attempt to share common substrings in the pool, so there should be no link between s1 and s2.
s2 ----X> "ab"
Am I clear?
Whether the VM ends up making both string referencesIt should be VM independent since string literals, and the string pool is described in the JLS:
point at the same string or not, is not your concern.
I'm not even sure different versions of the VM would
have to agree, so maybe at runtime depending on which
VM you used you might get different results.
But in my example, the constant "abc" should alreadySo you think that every time a String is created the VM is supposed to check the pool and point the reference at an existing value? So in this:
be on the pool, no?
So when I create 's2', the value should be retreived
on that pool, am I wrong (again)??
Exactly, that's what I'm trying to understand.So you'd also expect String.clone() (if it were accessible) to do nothing except:
Isn't it the r�le of this Pool: check if it can reuse
the Strings already created?
and violate the general contract for clone as well? (Read the specification for Object.clone())
Isn't it the r�le of this Pool: check if it can reuse the Strings already created?The JLS is clear about this:
Your example isn't a constant expression.To illustrate this point:
final String a = "a"; final String b = "b"; String ab = "ab"; System.out.println(a+b == ab); // returns true: Constant expression. String a2 = "a"; String b2 = "b" System.out.println(a2 + b2 = ab); // returns false: Not a constant expression