• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

passing object references

 
srikanth reddy
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Dharmesh Gangani
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Srikanth,
Is there any specific part of the code you are not able to understand OR you are facing problem with the entire code.
 
Prashanth Raghavan
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess the output will be 15 0 and 20.
[ August 11, 2005: Message edited by: Prashanth Raghavan ]
 
Marcelo Ortega
Ranch Hand
Posts: 528
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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):

 
Marcelo Ortega
Ranch Hand
Posts: 528
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry i ment 15 0
 
srikanth reddy
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 528
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic