Reputation: 125
StringBuilder str = new StringBuilder("Today");
str.append(" is ").append("a").append(" sunny ").append(" day.");
In the java code above, I understand that first I created an object of type StringBuilder. Then I used the object reference str to access the method append of the class StringBuilder. After this, I loose track. Is the method append used after str.append("is") inside the append method, or am I calling the same method in this class? Further, can anyone explain the flow of execution of the above statement. Which of the above append methods is executed first?
Upvotes: 3
Views: 1380
Reputation: 8014
StringBuilder str = new StringBuilder("Today");
str.append(" is ").append("a").append(" sunny ").append(" day.");
Here str.append(" is ")
returns object of StringBuilder
on which you are calling again append("a")
methnod.
str.append(" is ").append("a")
return again StringBuilder
reference and again you are calling append(" sunny ")
method and so on.
So basically you are chaining the methods and that's it.
Upvotes: 1
Reputation: 6452
Consider taking a look at the Builder Pattern(scroll down towards the end of the page). Basically the object always returns itself, so you can chain many commands.
Upvotes: 3
Reputation: 691665
str.append(" is ")
returns the StringBuilder itself. You're calling a method on the object returned by the method. It's the same as doing
user.getAddress().getStreet().charAt(0);
Except in your code, each append()
method call returns the same object, which allows chaining multiple method calls to the same StringBuilder.
Upvotes: 5
Reputation: 56809
The return value of append
method is the StringBuilder
object itself. So you can chain up the call and add more characters to the string. Otherwise, the code will be very hard to read, since you have to keep referring to the StringBuilder object every line.
Upvotes: 6