Click to See Complete Forum and Search --> : Objects are passed by Reference?


ParagW
March 7th, 2000, 09:01 AM
Hi,
I wrote the following code :
<javacode>
public class BugTest {

public Integer str;
public BugTest()
{
}
public BugTest(Integer st)
{
str=st;
}
public void aMethod(BugTest bt) {
bt = new BugTest(new Integer(10));
System.out.println("The handle inside method:" +bt);
System.out.println("The value inside method:" +bt.str.intValue());
}
public static void main(String[] args)
{
BugTest bte = new BugTest(new Integer(11));
System.out.println("The handle before method:" +bte);
System.out.println("The value before method:" +bte.str.intValue());
bte.aMethod(bte);
System.out.println("The handle after method:" +bte);
System.out.println("The value after method:" +bte.str.intValue());

}
}
</javacode>
It produces following o/p:

The handle before method:BugTest@a1d5ffb5
The value before method:11
The handle inside method:BugTest@a23dffb5
The value inside method:10
The handle after method:BugTest@a1d5ffb5
The value after method:11

As we can see, Handle of the Object passed to method remains unchanged but the Object itself is
updated. If Objects are passed by reference, what is the logic behind this. If its a reference the Handle should also have been updated.
Quite confused over this. (Was asked this at an Job interview!) Any inputs?

Cheers,

Parag

poochi
March 7th, 2000, 10:38 AM
> If Objects are passed by reference

No.. "Object References" are passed by Value.


> bt = new BugTest(new Integer(10));



You are creating a new Object and assign the new object references to "bt". You are
not modifying the already created one..

Check out the post , If you still find problem about it , post your question.
http://codeguru.developer.com/bbs/wt/showpost.pl?Board=java&Number=4113&page=&view=&sb=&category=

Poochi..