This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
13. String x = new String("xyz"); //one "xyz" is created in string pool, new String("xyz") will create another string 14. y = "abc"; //one "abc" is created in string pool 15. x = x + y; //one "xyzabc" is created
Joined: Dec 16, 2005
Yes, You are correct in K&B also explained the same.
Here is the question from whizlab, How many String Objects?. whizlab given answer is 4. but my answer is 5. pls correct me if am i wrong.
1.String s1 = "abc"; // first string 2String s2 = new String("xyz"); // second and third string 3. s2 = s1; 4. s1.toUpperCase(); // fourth string 5. String s3 = "abc"; 6. String s4 = s3.replace('a','A'); // fifth string in line 1 ,one object is created in heap and its reference is stored in string literal pool.this operation occurs at time when class is loaded in memory,as string literals are handled like constants at loading time.At runtime this reference is copied into local reference
in line 2 a new string object is created in heap and s2 refer to it,this operation occurs at runtime ,only 1 string object is created
in line 4 a new string object is created
in line 5 a local reference is created to object created in line 1,by copying into it reference from string literal pool,no new object is created,as string literals are interned ie.only 1 object is made for all string literals having same contents
in line 6 ,a new object is created ---------so total 4 objects are created
I agree with Mandeep. I felt whole point lies at the line 2.Normally it creates two objects on the heap.By assigning s2 to s1 changing the picture at line 3.After line 3 s2 should be considered as a normal string (I mean its not created using 'new' any more ). So at run time we have only one "xyz" object on the heap.