2

From what I understand, the String concatenation "+" operator in Java is implemented using Stringbuilder, such that something like :

String s = "foo" + "bar" 

internally compiles as :

String s = new StringBuilder().append("foo").append("bar").toString();

So I tried something like this :

String foo1 = "foobar";
String foo2  = new String("foobar");
String foo3 = "foo" + "bar"; 
char[] fooarray = {'f','o','o','b','a','r'};
String foo4 = new String(fooarray);

Next I tested these against each other using == operator. The results were mostly what I expected : foo2 and foo4 did not return "==" for any other String.

However , foo3 == foo1 returns true. What is the reason for this ? The StringBuilder class's toString method internall calls "new String" , so shouldn't foo3 be a unique object, just like foo2 ?

2
  • 11
    String concatenation of two string literals are done by the compiler, not at runtime. So writing "foo" + "bar" is the same as writing "foobar". It allows you to split a string literal over multiple lines, without performance penalty. Commented Oct 6, 2016 at 7:08
  • 3
    Also, if your Strings are final, then even, String s = s1 + s2 will happen at compile time if s1 and s2 are references to String literals Commented Oct 6, 2016 at 7:10

1 Answer 1

4

The reason why foo3 == foo1 returns true is because of String pooling.

When you concatenate string literals (even final strings that aren't literals) the concatenation happens at compile time, so when the program executes the values String foo1 = "foobar"; and String foo3 = "foobar";.

String pool or String table is a special area on the heap which stores String references.

Now, when you create String foo1 it is kept in the pool if there is no other string literal with value foobar. But in case of foo3 there is already a string literal with value foobar so foo1 and foo3 points to same object in the String pool, this is done to save memory.

When you create a String with new keyword the object resides on the heap but outside of String pool.

If you want a string created with new keyword to be in the String pool if same value already exists in the pool then you have to call String intern() method and assign back the reference to the String variable.

For more information - What is the Java string pool and how is “s” different from new String(“s”)?

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.