String s1=new String("Java"); /* 1st object created */
String s2="Tech"; /* 2nd Object */
s1+=s2;
I'm confusing here whether new object created or result stored in the previous object.
How many Objects created
String s1=new String("Java"); /* 1st object created */
String s2="Tech"; /* 2nd Object */
s1+=s2;
I'm confusing here whether new object created or result stored in the previous object.
How many Objects created
str1 += str2
is equivalent to doing the following:
str1 = new StringBuilder().append(str1).append(str2).toString();
Final call to toString will create a new object and the reference will be hold by variable str1 here in 3rd line of code. The earlier object in heap String("Java") will become ready for garbage collection.
Java is not similar to c in case of strings it creates a new object instead of modifying the existing objects. This is cause strings in java are immutable.
String s1=new String("Java"); /* 2 objects created as 'new' is used - s1 (holds reference to new String) and string literal "Java" */
String s2="Tech"; /* 3rd Object - "Tech", s2 just holds reference to it */
s1+=s2; /* 4th Object created, which is concatenation of s1 and s2. s1 holds reference to it.
So total 4 objects created.