File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes passing object references 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 "passing object references " Watch "passing object references " New topic
Author

passing object references

srikanth reddy
Ranch Hand

Joined: Jul 28, 2005
Posts: 252
can anybody explain the o/p???its a bit confusing ???

class Value
{
public int i = 15;
}
class Test
{
public static void main(String argv[])
{
Test t = new Test();
t.first();
}
public void first()
{
int i = 5;
Value v = new Value();
v.i = 25;
second(v, i);
System.out.println(v.i);
}
public void second(Value v, int i)
{
i = 0;
v.i = 20;
Value val = new Value();
v = val;
System.out.println(v.i + " " + i);
}

}

thanks
srikanth


Thanks & Regards<br /> <br />-Srikanth
Dharmesh Gangani
Ranch Hand

Joined: Feb 20, 2004
Posts: 30
Srikanth,
Is there any specific part of the code you are not able to understand OR you are facing problem with the entire code.


-=-=-=-=-=-=-=-=-=-<br />Thanks & Regards,<br />Dharmesh G.
Prashanth Raghavan
Greenhorn

Joined: Dec 10, 2004
Posts: 6
I guess the output will be 15 0 and 20.
[ August 11, 2005: Message edited by: Prashanth Raghavan ]

Prashanth R<br />Chennai
Marcelo Ortega
Ranch Hand

Joined: May 31, 2005
Posts: 519

I haven�t compiled it but the answer should be:

15 1

The method public void second(Value v, int i) takes a COPY of a reference and a COPY of an integer literal.

Don�t be fooled by this (in the second method):



SCJP 1.4, SCWCD 1.4, SCBCD 1.3, SCJD, SCEA/OCMJEA

Live life to an interface, not an implementation!
Marcelo Ortega
Ranch Hand

Joined: May 31, 2005
Posts: 519

sorry i ment 15 0
srikanth reddy
Ranch Hand

Joined: Jul 28, 2005
Posts: 252
i answer while compiling comes out to b 15 0 20

i didnt get from Value val = new Value();
v = val;

what happens exactly???

thanks & regards

srikanth
srikanth reddy
Ranch Hand

Joined: Jul 28, 2005
Posts: 252
i answer while compiling comes out to b 15 0 20

i didnt get from Value val = new Value();
v = val;

what happens exactly???

thanks & regards

srikanth
Marcelo Ortega
Ranch Hand

Joined: May 31, 2005
Posts: 519



look at the line commented with 2, here you are changing the value of the object which v refers to at the time (the one passed in the variable list). Then, v gets reasigned. When the method returns, 20 will be printed because the variable v in the second method (at 2) changed it before it got reasigned.

hope i explained myself properly.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: passing object references