i was just wondering if anybody could help me out with this :
StringBuilder s=new StringBuilder("0123456789");
s.substring(1, 2);
System.out.println(s);
s.delete(2, 8);
System.out.println(s);
the first Sysout gives 0123456789(although i expected a substring) but other Sysout gives 0189. I have noticed that also with some Time and Date classes.How can i figure out, when what form is going to modify original object (in this case s). Is this related to Mutability of objects? Is there any general rule? Thanks in advance HK
If you see the
substringmethod definition inAbstractStringBuilderabstract class which later extended byStringBuilderclass, you will find below code:From the method definition you can see that it is returning a new
Stringobject, the method is not working on actualStringBuildercontent. So their will no change in the content ofStringBuilderobject but rather a newStringobject will be returned.Now if you see
deletemethod definition insideStringBuilderclass it is:And the definition of delete in
AbstractStringBuilder(StringBuildersuper class) is :From the method definition it could be clearly understood that it is working on same
StringBuilderobject content and it is not returning a new object but rather the same object reference which is passed to it.