Joe McTigue wrote:
The reason is that Java passes parameters by value, not by reference. In the code above you have to references to the same StringBuilder (one in the main method, and one in the testRefs method). When you assign a value to a reference it only affects that reference, and any other references are left unchanged.
You may be getting confused in this example because both references happen to have the same name. If I re-write the code and change the names it may make it more clear.
So as you can see now, the StringBuilder reference in the main method is not the same StringBuilder reference in the testRef method.
When you call the testRef method, the value of sb is copied into localParameter. The value that is copied is effectively a pointer to the StringBuilder object. This means that both references end up pointing at the same object (so when you call methods on that object in testRef the effect of those calls can be seen in the main method). However assigning the value of null to localParameter only affects localParameter and leaves sb unchanged.
Edit: Beaten by 30 seconds, boo! :P