0

What is the difference between these two assignments, in terms of memory allocation and String pools.

String b = "sunil" + "khokhar";

and

String a = "sunil";
String b = a + "khokhar";
2
  • 1
    What do you think would happen? How do you think the compiler and the string pool would be different? Have you considered what difference using final might make? Commented Sep 24, 2014 at 6:46
  • what does it matter. what is your actual requirement for which you want to use the above approach. Commented Sep 24, 2014 at 6:54

2 Answers 2

2
String b = "sunil" + "khokhar";

both "sunil" and "khokar" will be concatenated and the value of b will be resolved during compile-time. So, "sunilkhokhar will be present in the String constant pool. and

String a = "sunil";
String b = a + "khokhar";

"sunil" and "khokar" will be compile time constants (and be added to the String pool). But b = a+"khokhar" will be done using StringBuilder and will occur at runtime. So, b will be present in heap and not in the String constant pool.

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

Comments

0

String is a final class every time you user "+" and "=" new object will be created. For Variable assignments, if value already exists in pool then reference will be returned along with Object.

4 Comments

Not every time. No, only when you are using a reference which is not final during concatenation. So, a + "khokhar" will be resolved during compile time if a is final.
I think in case of String b="sunil"+"khokhar" only one object is created having value "sunilkhokhar" and one entry in string pool which refer this object.
and In case of String a = "sunil"; String b = a + "khokhar"; two object is created and 2 reference in. @TheLostMind correct me if a am wrong
@SunilKhokhar - 3 String objects. "sunil" and "khokhar" will be in String constants pool and "sunilkhokhar" will be on heap. So, totally 3.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.