Beware: I'm not trying to compare if the characters are equals. Because I know how to use the String.equals() method. This question is about String reference
I was studying for the OCA exam when I started to learn about the class String and it properties as immutability, etc. According to what I read or may understand about String pool is that when a string is created Java stores this object on what they call String pool and if a new string is created with the same value it is going to make reference to the string on the String pool except is the case we use the new keyword as this creates a new reference even both string contains the same value.
For example:
String a = "foo";
String b = "foo";
String c = new String("foo");
boolean ab = (a == b); // This return true
boolean ac = (a == c); // This return false
To be clear what this code is making is on the first line of code it will create the String a = "foo"
and store this on the String pool, and on the second line of code it will create the String b
and reference to "foo"
because this already exist on the String pool. But line 3 will create a new reference of this string no matter if this already exist. Here is a little graphic example about what is happening:
The problem comes on the followings lines of code. When the string is created by concatenation does java make something different or simple == comparator have another behaviour ?
Example A:
String a = "hello" + " world!";
String b = "hello world!";
boolean compare = (a == b); // This return true
Example B:
a = "hello";
b = "hel" + "lo";
compare = (a == b); // This return true
Example C:
a = "Bye";
a += " bye!";
b = "Bye bye!";
compare = (a == b); // This return false
To watch the code running: (http://ideone.com/fdk6KL)
What is happening ?
EDIT
Fixing error on the Example B:
b = 'hel' + 'lo'
Adding clarification about the problem. It's not a comparison problem cause I know the use of
String.equals()
the problem is on the reference on the String pool
"Some Text" + i + "."
a thousand times. Do you think that deserves thousands of entries in the string pool? – TerrariumString a = "foo"
" is not correct. That line only creates the reference (variable pointing) to the string, which string itself was already in the string pool, whither it was placed upon class initialization. – GrinderyString
instance, such as an invocation ofnew String(...)
or a concatenation, creates a fresh, non-interned instance ofString
. "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 methodString.intern
." docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.5 Otherwise one must callintern
explicitly. Read the Fine Manual. – Grindery