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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With