Search code examples
javastringbuffer

How is a StringBuffer passing data through voids with no fields in the Class?


Given: Class has no fields, every variable is local. littleString was created by refactoring bigString in Eclipse:

public String bigString()
    {
        StringBuffer bob = new StringBuffer();
        this.littleString(bob);
        return bob.toString();
    }

private void littleString(final StringBuffer bob)
    {
        bob.append("Hello, I'm Bob");
    }

The method littleString should not be passing the StringBuffer back, but yet is is. What kind of Black Magic goes on here? This is breaking all rules of encapsulation that I know. I'm in shock, words fail me.


Solution

  • littleString isn't passing the object back -- it's just using the same object. Both the local variable bob in bigString() and the parameter bob in littleString() refer to the same object, so if you change one of those objects, the changes will appear instantaneously in the other because they're both references to the same object.

    The issue is that StringBuffers are mutable and have internal state associated with them. Some types of objects (such as Strings) are immutable, so you can safely pass them around as method parameters, and you know they won't ever get modified. Note that the addition of the final keyword doesn't help here -- it just makes sure that bob never gets assigned to refer to a different StringBuffer object.