Fiona
SCJP 6
Why to worry about things in which we dont have control, Why to worry about things in which we have control ! !
James Tharakan wrote:return and accept the updated value
Fiona
Paul Beckett wrote:java is always pass by value. That is the argument to a method for an object value is actually a COPY of the reference to the object.
Your method:
works because you are adding to the List that is referenced by the parameter l.
Try changing your code around:
(i) add "Hello" to the list defined in your main method
(ii) Modify the change(List) method so instead of adding an value to it create a new list. i.e. "l = new ArrayList<String>()".
(iii) Observe that your output still includes the value "Hello"
The reason it doesn't work for Strings (or wrapper classes) is because they are immutable.
Fiona
N Pats wrote: But what if we use some other object in place of these immutable objects? Would it behave like the List??
Sunil Kumar
> Think Witty <
Sunil Kumar
> Think Witty <
Sunil Kumar wrote:Before method A : referenceA points to ObjectA
Passing to method : referenceB is created pointing to objectA
In Method : referenceB points to ObjectA (unless you assign a whole new object to the referenceA)
you make changes to ObjectA
Out of method now : referenceA still points to ObjectA . Hence changes in ObjectA are reflected back.
Think diagrammatically in terms of allocation.
Fiona
This cake looks terrible, but it tastes great! Now take a bite out of this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
|