The reason is, the method replace() creates a new String object allocated from the heap.
In fact the allocation from String pool and subsequent optimization happens only in case of String literals. When we write a statement like,
String s3 = "arit";
s3 is assigned a reference to a String object stored in the String pool for the literal "arit". But in case of a statement like,
String s5 = new String("arit");
we are not assigning the variable s5 with a direct reference to String literal "arit". Here what happens is - a new String object is created with a value "arit" and s5 contains reference to this object. The allocation is from the heap and not from the pool. The same is true in case of replace() method.
Originally posted by Bharatesh H Kakamari:
String s1 = new String("amit"); // allocated from heap
String s3="arit"; //allocated from String pool
String s4="arit"; // no new reference created
String s2 = s1.replace('m','r'); // AS "arit" ALREADY EXISTS, SHOULD IT NOT BE ALLOCATED REFERENCE OF s3 ?
System.out.println(s2==s3);
System.out.println(s3==s4);
WHY DOES IT PRINT "false" FOR FIRST SOP ?