This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Hi friends I've aquestion here .Can someone help??? My questions 1.Here when i'm assiging a3=7; the change is visible both in a1 and a2 as a1 =a2 .after the fix(a1) method returns . the ouput is 15 ,15..
[ September 05, 2005: Message edited by: shanthisri mocherla ] [ September 05, 2005: Message edited by: shanthisri mocherla ]
Lets break up your code and see whats happening, may be that might answer your questions.
Now you call the method fix(a1) and pass a1 as an argument, what you are passing is infact a reference to object a1. That reference is picked up by array a3, which you define here long fix(long a3). So now the picture looks like.
You change a=7, so
Now, you return from method fix() and a2 picks up the reference, so
Yes, arrays are objects in Java that store multiple variables of the same type. Arrays can hold either primitive or object references, but the array itself will always be an object on the heap, even if the array is declared to hold primitive elements.
Joined: Sep 05, 2005
I've one more question on array reference passed to the methods //the output is 1,3
//the output is 3,1
Can anyone expalin why in the first example the values are not changing? [ September 05, 2005: Message edited by: shanthisri mocherla ]
Hi Shanthisri, An easy way to remember arrays and references to them when passed to methods is like this: 1. Ofcourse a copy of the reference (pointing to the array object) is passed when the method m1 in the above examples is called. 2. So references i1 and i2 in the method m1 is different from the references i1 and i2 in the main method. (it is like the array object is a Lock and the references are the Keys to open the Locks - so here we have two sets of Keys that open the same lock and both have the same name but in different methods) 3. As long as the i1 and i2 references in the method m1 are changed (for example i1 = i2 or int i3 = i1 etc), it does not affect the original array content (declared in the main method). 4. But if the i1 and i2 references in the method m1 change the individual array element values, it reflects in the original arrays. (For example i1 = i2 -> this will change the value in the original array declared in the main method). So look for what is being changed the reference by itself or the array elements pointed by the references. Hope this helps...and so you can see the results as they are.