I am bit confused about string object creation. Can someone tell me, how many String objects get created in below 2 cases?
1)
String s = new String("abc");
s = s + "xyz";
2)
String s = new String("abc");
String s1 = "xyz";
I am bit confused about string object creation. Can someone tell me, how many String objects get created in below 2 cases?
1)
String s = new String("abc");
s = s + "xyz";
2)
String s = new String("abc");
String s1 = "xyz";
First case:
String s = new String("abc");
s = s + "xyz";
You have:
"abc"
is a string literal and is interned => one string instanceString s = new String("abc")
creates another string "abc"
that is stored in the heap => another string instance;s = s + "xyz";
you have "xyz"
as one string literal which is interned and another string on the heap is built with the concatenated value "abcxy"
which is another string.You have 4 strings created in total with the old value of s
being discarded. You remain with the "abc"
and "xyz"
interned strings and string "abcxyz"
which is stored in s
.
Second case:
String s = new String("abc");
String s1 = "xyz";
You have:
"abc"
is a string literal and is interned => one instanceString s = new String("abc")
creates another string "abc"
that is stored in the heap => another instanceString s1 = "xyz";
you have "xyz"
as one string literal which is interned and s1
points to it.You have 3 strings created in total. You remain with two interned strings "abc"
and "xyz"
, another "abc"
stored in the heap and referred by s
while s1
points to the interned "xyz"
.
You might also have a look at this for some basic explanations: The SCJP Tip Line: Strings, Literally
After the execution of 1) you have one String object, after 2) you have two.