shweta patiljadhav wrote:what would be the output? if on StringBuilder methods are called from left to right here delete() is called first. and why it's output is not 12SUN4512S5?
Why it is appending out put of delete method twice?
Chained methods will definitely be called from left to right. And that's not only limited to StringBuilder's methods, but applies to any object. Here's an example of a StringBuilder
Output:
!skcor avaJ
And you can do the same with strings as well
Output:
abc rOcks? Jabcvabc rocks!
Remember: there is one very important difference between the first and second code snippet. In the first code snippet you are using a StringBuilder which is a mutable object, so that means that every method call will manipulate the same object. In the second code snippet you are using a
String and as you know a String object is immutable. So every method call results in another String object being created. Only the result of the last method call
replace("a", "abc") is assigned to the reference variable
res and thus is still reachable; all other objects are unreachable and thus eligible for garbage collection. It would be a nice exercise to list all unreachable String objects from the second code snippet
Now in your code snippet
you didn't use chained methods at all. And that's why these methods are not executed from left to right. In order to call the
append method, you need of course to know the String you want to append. That's why the
delete method is executed before the the
append method: the result of the
delete method is required to be able to execute the
append method.
Why this code snippet prints
12S512S5 is already well explained by Liutauras, so I won't explain it again. But I'll do a little pop quiz with you to see if you fully understood everything explained in this topic
What will be the output of the above code snippet if we replace the first line of the
main method to
If you think the code snippet doesn't compile, just say so (and explain why).
Hope it helps!
Kind regards,
Roel