Friday, 22 April 2016

How many String objects ?


String s1 = "abc";
// Creates 1 obj in String pool (s1 will refer to object in String pool)

String s2 = new String("xyz");
// Creates 2 new objects, one in String pool and one in heap (s2 will point to object on heap)

s2=s1;
// No new object is created; only assignment will take place

s1.toUpperCase();
// Creates 1 obj

String s3 = "abc";
// No object created (s3 points to existing object in String Pool)

String s4 = s3.replace('a','A');
// Creates 1 new object



Total objects created : 5

No comments:

Post a Comment

Note: only a member of this blog may post a comment.