File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Javabeat mock 2, question 14 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Javabeat mock 2, question 14" Watch "Javabeat mock 2, question 14" New topic

Javabeat mock 2, question 14

Rachil Chandran
Ranch Hand

Joined: Mar 05, 2006
Posts: 67
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 ]

SCJP2 96%
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2398
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

Joined: Feb 28, 2007
Posts: 1710
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?

[ April 09, 2007: Message edited by: Chandra Bhatt ]

Rachil Chandran
Ranch Hand

Joined: Mar 05, 2006
Posts: 67
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.
I agree. Here's the link:
subject: Javabeat mock 2, question 14
It's not a secret anymore!