| Author |
Are primitive arrays passed as reference
|
Anil Deshpande
Ranch Hand
Joined: Jan 13, 2008
Posts: 117
|
|
This is reaslly stupid of me. I know there is now concept of pass by referenc in Java. But I am gettig confused after looking at the code.
The out put is modified array. How is it happening. If I am passing the array of strings then also also I am getting the same behavior (that code is not prsent here. But in that case the method takes array of String and modifies the String array anre returns the the String array. )\
So are array, be it of premitive or objects, passed by reference.?
Please let me know.
Thanks and Regards,>
|
Anil Deshpande
SCJP 1.5, SCWCD 1.5
|
 |
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 10043
|
|
let's start here:
EVERYTHING in java is pass by value.
Now that we have that cleared up...we have to talk about what that means. When you pass what you think of as an object, you are really passing the value of the reference. That's kind of like saying you give the address to the method.
Let's say I have a house object. My reference is a notecard with my home address on it. If I say "Anil, go to this address and tell me what color my house is", you would go to that address, look at my house, and say "Your house is white".
Now i give the address to a painter. He goes to my house, and paints it blue.
THEN I say "Anil, go to this address and tell me what color my house is", you would go, look, come back and say "your house is blue".
When you pass the array into the method, the method can change what is IN the array, but can't change what address the array refers to.
If we go back to the address cards...I have a notecard with my home address. I give a COPY of that notecard to the painter. He can erase the address on that card and write a new address on the card, but that does not change what is on my original copy. So if you did this:
The two "code to print array" lines would produce the exact same output.
|
Never ascribe to malice that which can be adequately explained by stupidity.
|
 |
Anil Deshpande
Ranch Hand
Joined: Jan 13, 2008
Posts: 117
|
|
Thanks a lot Fred...
I liked your analogy oh "House painting". Made it very easy for me to understand
|
 |
 |
|
|
subject: Are primitive arrays passed as reference
|
|
|