Search code examples
javastringbuffer

StringBuffer method parameter - doesn't change value


I know that String is immutable and it's value can't be changed, but why does the value of the below StringBuffer doesn't change when sent like a method parameter. From my understanding it should have changed with the new value "bb". Thank you for your help.

class Ideone {

    public static void main (String[] args) {

        String s = "aa";
        StringBuffer sb = new StringBuffer("aa");
        modify(s, "bb");
        modify2(sb, "bb");
        System.out.println(s);
        System.out.println(sb);
    }

    public static void modify(String s, String ss) {
        s = ss;
    }

    public static void modify2(StringBuffer sb, String ss) {
        sb = new StringBuffer(ss);
    }
}

Solution

  • The universal rule in Java is that you cannot change the reference of an object passed into a method, but you can change its contents.

    public static void modify2(StringBuffer sb, String ss){
    

    This method takes a copy of a reference to a StringBuffer. Changing that reference to point to an object has no effect whatsoever on the original object. But if you implemented it as

    sb.clear();
    sb.append(ss);
    

    then it would work.

    Again, the rule is that reassigning an object passed into a method with = does nothing to the original object, but you can change the contents of that object just fine.