This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes result doesnt match Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "result doesnt match" Watch "result doesnt match" New topic
Author

result doesnt match

Sandeep Mali
Greenhorn

Joined: Sep 03, 2005
Posts: 6
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

Joined: May 05, 2005
Posts: 162
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

Joined: Jan 29, 2003
Posts: 8791
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
Sandeep Mali
Greenhorn

Joined: Sep 03, 2005
Posts: 6
Thanks for the replies!

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

Regards,
Sandeep.
 
 
subject: result doesnt match
 
Similar Threads
how to explain the following question?
Exam on 9th july -- pl help
Explanation Required
Pass by val/ref ?
Passing Values