Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why StringBuilder acting like pass by reference

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.

like image 912
Anoop Avatar asked Feb 11 '13 17:02

Anoop


1 Answers

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.

like image 200
Gilbert Le Blanc Avatar answered Sep 28 '22 07:09

Gilbert Le Blanc