• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why is the output ........

 
Karu Raj
Ranch Hand
Posts: 481
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class ValHold
{
public int i = 10;
}
public class ObParm
{
public static void main(String argv[])
{
ObParm o = new ObParm();
o.amethod();
}
public void amethod()
{
int i = 99;
ValHold v = new ValHold();
v.i=30;
another(v,i);
System.out.println(v.i);
}//End of amethod
public void another(ValHold v, int i)
{
i=0;
v.i = 20;
ValHold vh = new ValHold();
v = vh;
System.out.println(v.i+ " "+i);//ABC
}//End of another
}

Why is the output at ABC for v.i as 10 not 20 ?
 
Sandeep Chhabra
Ranch Hand
Posts: 340
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

in another method you create new valhold obj
and assign its ref to v.
since the newly created obj has the value of i=10 the and the same object reference is assigned v
therefore v.i=10;

but in main u'll get the valuf of v.i=20.

try to evaluate the problem step by step

Hope this helps

Sandy
[ September 18, 2005: Message edited by: Sandeep Chhabra ]
 
Karu Raj
Ranch Hand
Posts: 481
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so you mean that as the new instance of class is created
[ValHold vh = new ValHold();]

so it holds the instance variables i=10; RIGHT???/

if the new instance of class is not created
then the value of v.i=20 is printed right???
 
Sandeep Chhabra
Ranch Hand
Posts: 340
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have got the point now...

Sandy
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic