Reputation: 486
check this code
public class StringbuilderDoubt {
public static void main(String args[]){
new StringbuilderDoubt().methodTest();
}
public void methodTest(){
String str=new String("Default");
StringBuilder sb=new StringBuilder();
sB1(str,sb);
sB2(str,sb);
System.out.println(str+".........."+sb);
}
private void sB1(String str1, StringBuilder sb1){
str1+="str1";
sb1.append("sB1");
}
private void sB2(String str2, StringBuilder sb2){
str2+="str2";
sb2.append("sB2");
}
}
Output is: Default..........sB1sB2
Why StringBuilder is working like pass by reference?
In methodTest I am passing two objects string and string builder. String is pass by value but StringBuilder looks like pass by refence and StringBuilder object from calling method getting changed.
Upvotes: 6
Views: 15160
Reputation: 21748
Because it is passed by reference. The reference to the StringBuilder
is passed by value. You can add characters and they will be in the instance after the method returns. Same way you can pass a Collection and add values inside the invoke method - these will be preserved. You can also call setters or assign public fields, such changes will also persist after return.
The reference to String
is also passed by value so assigning a new value to this reference has no effect after the method returns.
Upvotes: 1
Reputation: 51445
When you pass a StringBuilder instance to a method, the instance value is passed by value. As you've seen, you can append characters to the StringBuilder instance inside of the method without returning the instance value.
You can also return the StringBuilder instance value if you want, but it's not necessary. It hasn't changed.
This "pass by reference" also works for most of the Collection classes (List, Map), and for your own classes that have getters and setters.
If you don't want this behavior, you have to make deep copies of the instances you pass. You would do this if you return a Collection class from a public API.
Upvotes: 5
Reputation: 178263
I don't see anything wrong with StringBuilder
here.
Nothing happens to the string referred to by the str
reference. In your sB1
method, you have a local reference str1
. The "+=" operator returns a new String, but the original string, being immutable, is not changed. The same thing happens in your sB2
method.
So, your variable str
still contains only "Default".
Upvotes: 1