This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
why does the following program print s=aaa sb=bbbaaabbb. It will print s=aaa because Strings are immutable and whatever changes we do to str in TestRefs method will not be reflected back in the main.
But i want to know why will it print sb=bbbaaabbb.Whatever changes we do to stringbuilder in testRefs is reflected back in the main.So after line sb.append(str) we are setting sb=null , so how come it prints sb=bbbaaabbb when it's been set to null.
Rohan Deshmkh wrote:why does the following program print s=aaa sb=bbbaaabbb. It will print s=aaa because Strings are immutable and whatever changes we do to str in TestRefs method will not be reflected back in the main.
It's true that String is immutable, but that's not why main() doesn't see the changes. The reason is that Java passes only by value. Primitives are passed by value and references are passed by value. This means that when you change the value of a parameter inside a method, the caller doesn't see the change, because the method parameter's copy of that variable is completely separate from the caller's copy.
Note that both the caller's variable and the method parameter point to the same object though. The object doesn't get copied, just the reference.
why will it print sb=bbbaaabbb.Whatever changes we do to stringbuilder in testRefs is reflected back in the main
This line should be like..
Whatever changes we do to stringbuilder object in testRefs is reflected back in the main
That's kind of confusing wording.
If we change the value of the sb variable--that is, assign a different reference value to sb, so that it points to a different object--then the caller will not see that, since our variable is completely independent from the caller's.
If we change the state (the "contents") of the object that sb points to, such as with sb.append, then the caller WILL see that, since both variables point to the same object.
By setting sb=null , we are saying that sb will not point to anything.So when it does not point to anything
Only our local copy of sb. It does not affect ther caller's variable. They're two completely separate, unrelated, independent variables that pointed to the same object when the method was called, but by setting sb to null inside the method, we're just saying that this particular variable now does not point to any object--we're not affecting the caller's variable, and we're not affecting the object.