System.out.println(s2.replace("able","ability"));
In above line, A new string returned and printed.
Because String#replce()
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
s2.replace("able", "abled");
It does the replace operation but,not assigned the result back.So the original String remains the same.
You see the result if you assign the result.
like
String replacedString = s2.replace("able", "abled");
System.out.println(replacedString );
or
s2= s2.replace("able", "abled");
System.out.println(s2);
Update:
When you write line
System.out.println(s2.replace("able","ability"));
That s2.replace("able","ability") resolved and returned String passed to that function.
ImmutableandRValue!String s3 = s2.replace("able", "abled");you will get the result. You have some below explanations.