• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

call by reference

 
mohammad shaid
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Source-- javacaps.com



The output is 10020;;; I am confused with this output and call by reference... can anyone xplain ???
 
Rajeev Rnair
Ranch Hand
Posts: 310
1
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mohammed,
the first one prints "10"

This creates a new ValHold() and assigns to v; so v.i is 10.

second one prints local variable "i" and it is "0"


This method is trying to assign a new reference to the passed one. However it CANNOT change the original reference "v". But the "v.i = 20; " is still valid because the calling method can change the values of member variables (but not the reference). So the third one prints 20.
 
rewati raman
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Shaid
lets start with main method first and lets see the flow of control.
ObParm o = new ObParm();
o.amethod();
we know what happened above.
now in amethod
int i = 99; is creating a local variable of this method.
then v object of valhold is created
then v.i=30;
mean the i of v object has been changed to 30 as it is public. this dosnt mean the local variable of amethod is 30, that is still 99.
now another method is called. so the rest of code will follow only after the complete execution of another method.
in another method

i=0; is done which is of no use.
now the another method was passed an object v
code is changing v.i to 20 that mean before in amethod when it was changed to 30 is changed to 20 now.
another object of vhal is created that is vh
and vh is coppied to v.
now
v no more holds the previous object. now it is reffereing to new object . which was created recently.
so according to vhal the new object's i data member shud be 10
so when next print of v.i is executed it gives 10
then value of i
which was changed to 0
so we have now
100
now amethods last statment is executed that is v.i which was last changed to 20.
as v=vh wont be valid in this block. v was refrence in another
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
mohammad shaid wrote:I am confused with this output and call by reference... can anyone xplain ???


read this FAQ entry
 
mohammad shaid
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Rajiv and Revati fo your efforts to explain.. i get the concept now.. Thanks a lot Friends..
 
mohammad shaid
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And thanks Seetharaman..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic