• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Object reference questions...............

 
mahesh zarkar
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For the code below I am kind of getting confused as to why the answer prints 10, 0, 20. I know why it is "10", and "0" but not sure why the last 20 bcos I am not sure why "System.out.println(v.i);" still referes the old ValHold object.
Please advice...........

 
Stefan Koeltze
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!
I think that iff you call amethod(v,i) you give only a COPY of the reference v (via a kind of stack) to that object. After return you have still the original reference to that object.
Hope it helps...
 
Rick Salsa
Ranch Hand
Posts: 173
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mahesh,
The reason it gives you twenty is because you passed another() a Valhold object. Inside that method, we change the value of v.i = 20, then assign a new reference to the v object. Let's look at the two methods:

We passed the ValHold object (1) into the another()method. At 2, we assign it a new value of 20. At 3, we assign a new reference to v. This is a completely new object. So any changes to this will not affect the object we create at 1. So at 4, it is printing out the value of the object at 1, whose value is 20, which was set at 2.
I hope that explaination didn't confuse you. Let me if it did, and I'll try explaining it another way.
/rick
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic