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";
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";
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.
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.