How many objects are created ?
// "xyz" is interned , JVM will create this object and keep it in String pool String x = "xyz"; // a new String object is created here , x still refers to "xyz" x.toUpperCase(); // since char literal `Y` is not present in String referenced by x , // it returns the same instance referenced by x String y = x.replace('Y', 'y'); // "abc" was interned and y+"abc" is a new object y = y + "abc"; System.out.println(y);
This statement returns a reference to the same String object
String y = x.replace('Y', 'y');
Look at the documentation:
If the character oldChar does not occur in the character sequence represented by this String object, then a reference to this String object is returned. Otherwise, a new String object is created that represents a character sequence identical to the character sequence represented by this String object, except that every occurrence of oldChar is replaced by an occurrence of newChar.