views:

243

answers:

4

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.

+6  A: 

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.

Adam Rosenfield
A: 

It's not passing anything back. It's modifying the StringBuffer you passed a reference to. Objects in Java are not passed by value.

Chuck
Uhm, all parameters in java are passed by value:See http://www.yoda.arachsys.com/java/passing.html and http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#17996
whaley
Yes, but the value passed is a reference. The object is not passed by value — the reference still points to the same object.
Chuck
+1  A: 

If you meant why does the string buffer get modified, it's because you were passing a reference to the string buffer, which allows you to call the public method append which modifies the string buffer object.

mweiss
A: 

the answers above pretty much got it, except one little thing hasnt been mentioned: java lacks "const-ness", meaning you want an object to be unmodifiable.

"final" is close, but it still doesnt do the job properly. What the code snippet showed is the kind of error that can happen if you have mutable objects passed in as parameters to other methods. This can be fixed either by having immutable objects, or if there is some kind of new keyword added for deep const-ness.

Chii
You can easily write immutable classes. I agree it's not the same as const-ness, but it gets you very far.
Joachim Sauer
new String(bob.toString()) makes it unmodifiable. If bob ware a collection then Collections.unmodifiableCollection(bob) would have made it unmodifiable. Well it gets real close. According to Hardcore Java, nothing will make a mutable object totally unmodifiable.
WolfmanDragon