Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • 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 from JavaRanch scjp MockTests.. its a random question..



Options are :
1) 10030
2) 20030
3) 209930
4) 10020

and Option 4 is correct.. how is it that 20 is being printed(appended) to the output.. can someone please xplain me the call by reference scenario here...
 
Anju Bhaskar
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

When passing the valHold instance into a method, (Since it is an object, pass - by reference will occur), it will create another copy of reference. Name of that reference is also v. because in the method definition, valHold parameter name is v. But these two references will be different. but referring to same object.
And v mentioned in the method definition will be local to method 'another'. In the method another(), you are changing the value of v as 20. So original object's i value get changed to 20.
when v = vh, local v i.e. the parameter v mentioned the another() method definition will get changed.
No change for the v in the amethod(). it iwll points to the same object.
So, we will get the anwer 20 for the third sysout.


 
Roberto Perillo
Bartender
Posts: 2271
3
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Howdy, Anju. First of all, I'd like to welcome you to our JavaRanch!

Now, Mohammad, I'd kindly like to ask you to carefully choose the appropriate forum before asking a question. Also, please choose a meaningful subject line for your question. This way, the forum is better organized, you get a good answer for your question faster and it is also able to help more people that have the same doubt as you! For general informations about how to ask questions here in the ranch, please take a look here.

Let's move this over to the SCJP forum.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic