This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

result doesnt match

 
Sandeep Mali
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Chandra Sagi
Ranch Hand
Posts: 162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Thanks
Chandu
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sandeep Mali
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the replies!

Well the explainations arent exactly simple but I do get the idea.

Regards,
Sandeep.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic