Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Passing Object reference

 
prerna boja
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,


Can anybody please expalin me the following program as how I am getting the output.The progem is running correctly but I need an explanation as I am cofused with passing an object reference. How v.i=15?

class Value
{
public int i=15;

}

public class Test
{

public static void main(String args[])

{

Test t = new Test();
t.first();

}

public void first()

{
int i=5;
Value v= new Value();
v.i=25;
second(v,i);
System.out.print(v.i);

}

public static void second(Value v,int i)
{

i=o;
v.i=20;
Value val = new Value();
v=val;
System.out.print(v.i + " "+ i);

}
}


Output : 15 0 20
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
On line 37 (in the method second), v.i = 15 because v is a reference to the object created on line 35, which has an i value of 15.

On line 26 (in the method first), v.i = 20 because v is a reference to the object created on line 23

Note that the two vs are different -- they are references with the same name that reference the same object, but they are different references. You would get the same results (an things mightl be a little clearer) if the method second were written as:

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic