Hi All, I've a question regarding string buffer. Code is as below.
I remember posting of this question before and somebody mentioning that 'a' and 'b' are passed by value or something. But I though in java all objects are passed by reference. Then why final value of 'a' and 'b' are 'One more' and 'two' and not 'One more' and 'one more'. Thanks in advance. Niral
Hi.. ) Well, when you pass an Object to a method you passes his reference, but you just can use this reference you can't change it like b=a because he is changing the reference from parameter b not the original object b passed through it... when you do a.append you change a because you are calling a method from the object you passed, but when you do b=a you are trying to change the reference from original object that U can't do it... because of this you change the value of a but the value of b remains the sabe because the assignment b=a doesn't change the original reference...
Java passes arguments by value,moreover,they are copy values of the original values,so when you pass refernce values a and b into the swap() method,actually the copy version a' and b' are passed into swap, at this point both a' and a reference to the object "One", b' and b reference to "Two". After append() method is executed, the result is that a' and a both referenct to "One more" (object "One" is changed). The next line, b' is assigned to a', so b' also refernce to a'(==a),but refernce value b remains unchanged!
Hi there: Also note that for same variables: 1. If you pass them to a method, local copies are is created. Any changes to local copy is not reflected in the original copy when control come out of that method. However if that variable is referencing an object and you manupilate that object from within the method, the object is changed for good. 2. If you DO NOT pass variables to method but they are accessable from within the method under consideration, any changes made to these variables will be permanent when control comes out of that method. Of Course, any changes to the refered objects will be permanent as well.
[ August 27, 2002: Message edited by: Barkat Mardhani ]