I came across a question in a mock test which is as follows.
When run it prints "Java more" for a and "Rmi" for b. But inside the swap()when I put a print statement I see the value of b is "Java more".why the change to variable a is reflected in main()and not the change to b? Can some body explain? Thanks Liza
Hey Lisa Inside methods we only have copies of references or primitive types.So in the method u assigend method's copy of "a" to be not the original "a" reference 'a' in main is still pointiong to original object . I hope this helps regards
Originally posted by denish mehta: Hey Lisa Inside methods we only have copies of references or primitive types.So in the method u assigend method's copy of "a" to "b" not the original "a" reference .'a' in main is still pointiong to original object . I hope this helps regards
But then Denish when we append to the variable a inside the method ,how come we get the changed value in main?both a and b should retain their unchanged values once they are out of scope.That is what confuses me.
U r missing the whole point here.In passing references as arguments the referneces does get copied not the object and the copied refernece still points to the same object.So any change u make using this copied reference to the object effects the object .U actually get two references to the same "object". And also u assgined b=a after changing the String buffer Regards Denish
Hi Liza, Both 'a' and 'b' are passed as copies of references to StringBuffer objects. In the method, a.append(" more") changes the actual object pointed to by 'a'; the same object 'a' in main() points to. However, the code 'b = a', 'b' is a copy of the original 'b' reference in main(). The assignment causes the method variable 'b' to point to the original 'a' object BUT it does not change the original reference variable 'b' in main(). Hope that helps. There's an article, Understanding that parameters are passed by value and not by reference that has a good explanation of how the values are passed. ------------------ Jane Griscti Sun Certified Programmer for the Java� 2 Platform