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 Object reference questions............... 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 "Object reference questions..............." Watch "Object reference questions..............." New topic

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

mahesh zarkar

Joined: Feb 14, 2002
Posts: 24
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...........

In search of Excellence.
Stefan Koeltze

Joined: Feb 08, 2002
Posts: 14
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

Joined: Jul 17, 2001
Posts: 173
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.
I agree. Here's the link:
subject: Object reference questions...............
It's not a secret anymore!