How Java String pool works when String concatenation?

Viewed 5284

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: http://cdn.journaldev.com/wp-content/uploads/2012/11/String-Pool-Java1.png

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

  1. Fixing error on the Example B: b = 'hel' + 'lo'

  2. 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

2 Answers
String a = "ef";
String b = "cd" + a;
        
System.out.println("cdef"==b); // false
        
String c = "cd" + "ef";
        
System.out.println("cdef"==c); // true

when intern() method is invoked on a String object, It will try to find a String with the same sequence of characters in the pool.

if the String Pool already has a String with the same value then the reference of that String from the Pool is returned, otherwise the string is added to the pool, and the reference is returned.

String concatenation will only intern the strings if the expression is a Constant Expression

"cd" + a // is not a Constant Expression
Related