Hi Folks could someone explain why the value of v.i in the last print statement is 20 and not 10. Here's my code(please excuse me if its a little lengthy):
Thanks, Sandeep Mali.
Joined: May 05, 2005
The result look like
Value of v.i in amethod:30 value of v.i in another:10 Value of v.i in amethod:20
Since v.i in another() method is a local reference we have 10 printed there, but outside the method the value is 20.
Joined: Jan 29, 2003
I got this result:
In amethod you create a ValHold and set i=30. That display makes perfect sense I bet. Then you call another. The tricky bit is what gets passed from amethod to another: a copy of the pointer (reference) to the first VH instance. Not the VH instance, not a pointer to the VH instance, but a copy of the pointer to the VH instance.
When another changes the value from 30 to 10 it changes the original VH instance because its copy of the pointer points to the original instance.
When another creates a new VH instance it changes its copy of the pointer to point to the new VH instance. This doesn't change the original pointer to the first VH instance so amethod's pointer still points to the first VH instance which now has a value of 10. another's pointer points to the new VH instance with a value of 20.
I said this was a tricky bit. Actually it's a dead simple rule: Java always passes "by value" a copy of the parameter to the called method. With primitives it passes a copy of the primitive. With object references it passes a copy of the object reference.
It seems I've been able to say that in fewer words in the past. Lemme know if it was clear enough this time.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joined: Sep 03, 2005
Thanks for the replies!
Well the explainations arent exactly simple but I do get the idea.