Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Javabeat mock 2, question 14

 
Rachil Chandran
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given this program, the output is to be determined



The answer is given as:

Local New Instance (I tried running the program and verified this is right).

My question is, shouldn't the "Local" change to "Local Add" after the call to method()?

Thanks in advance
[ April 09, 2007: Message edited by: Rachil Chandran ]
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All parameter passing in Java is by value.

When the parameter is a reference type, then a copy of the reference is sent.

In the method, you modify the formal parameter s, but that doesn't modify what the actual parameter points to.
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rachil,



Here you go...

1- There is one class variable s, assigned value "Instance";
2- Inside main() you created Test4 object and assigned it to t reference variable;
3- You reassigned class variable s = "New Instance";
4- Now local variable whose name is same as class variable, gets birth
and you assign it a value "Local".
5- Because you have now local variable s, what you pass to method() is local
variable s. (Test14.s == "static variable s", t.s = "static variable s" and
only s = "local variable s" and t=null then t.s = still static variable s)
6- In the method() effect of adding "Add" to passed String will have local
effect (passed by value concept).
7- In the main() method now you would have got...
s = "Local"
t.s = "New Instance"


Does this help you clear your doubt?


Regards,
cmbhatt
[ April 09, 2007: Message edited by: Chandra Bhatt ]
 
Rachil Chandran
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Keith and Chandra.

I got a bit confused because I was thinking in terms of a normal object.

For instance, if myObj is an instance and has an attribute 'a', changing the value of a through a passed reference

void method(MyObj o){
o.a = 10;
}
would actually change it in the myObj (method(myObj)).

The question I asked was more like rassigning o to some other instance. Don't know what I am to do in the actual exam if i make silly mistakes like these.

Thanks a lot for your replies.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic