Case 1 : literal VS Object

To be clear what this code is making is on the first line of code it will create the String s1 = "Cat"and store this on the String pool, and on the second line of code it will create the String s2 and reference to "Cat" 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.


Case 2:

Case 3 :

StringBuffer operates on Same Object .


Case 4:

When concatenating two string literals "a" + "b" the jvm joins the two values and then check the string pool, then it realizes the value already exists in the pool so it just simply assign this reference to the String.


Case 5: (+= uses StringBuilder Inside to Create & Append String)

Your example C is kind of different tho, because you’re using the += operator which when compiled to bytecode it uses StringBuilder to concatenate the strings, so this creates a new instance of StringBuilder Object thus pointing to a different reference. (string pool vs Object)

Oracle Says, To improve performance, instead of using string concatenation, use StringBuffer.append().String objects are immutable



It’s better to use StringBuilder (it’s an unsynchronized version; when do you build strings in parallel?) these days, in almost every case, but here’s what happens:

When you use + with two strings, it compiles code like this:


To something like this


for example, you might be using many different appending statements, or a loop like this:

In this case, a new StringBuilder instance, and a new String (the new value of out – Strings are immutable) is required in each iteration. This is very wasteful. Replacing this with a single StringBuilder means you can just produce a single String and not fill up the heap with Strings you don’t care about