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";
SylvainL
  • 3,926
  • 3
  • 20
  • 24
Sunil Khokhar
  • 370
  • 1
  • 5
  • 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? – Peter Lawrey Sep 24 '14 at 06:46
  • what does it matter. what is your actual requirement for which you want to use the above approach. – vikeng21 Sep 24 '14 at 06:54

2 Answers2

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.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
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.

  • 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*. – TheLostMind Sep 24 '14 at 07:08
  • 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. – Sunil Khokhar Sep 24 '14 at 07:21
  • 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 – Sunil Khokhar Sep 24 '14 at 07:23
  • @SunilKhokhar - 3 String objects. "sunil" and "khokhar" will be in *String constants pool* and "sunilkhokhar" will be on heap. So, totally 3. – TheLostMind Sep 24 '14 at 07:25