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
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