• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

strange behaviour of reference variable when passing to a function

 
rahan jain
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Value

{

public int i = 15;

}

public 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);

}

}




Output is ::
15 0
20




why last output is 20 ??

please help
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. You are passing a reference of object v to the method "second".
2. You are setting its "i" member variable to 20
3. You are setting v reference to a new reference, but remember that eveything in java is passed by value. So even if you assign v to a new reference, it won't change outside the method.
4. In main, after calling "second", v's reference is still the same, so the ouput is 20.

You can try to check v's reference before and after calling "second", with System.out.println(v)
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15216
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all, when you post code, please put it between [ code] ... [/ code] tags, so that the forum software automatically formats it.

What output did you expect, why do you think 20 is strange?

Arguments to methods are passed by value in Java. That means that not the variable itself is passed, but just the value of the variable, copied into a new variable. With primitives like int this is easy to understand.

Note that the variable v in your method called first() is a reference variable. It points to an object of type Value. When you pass v to the method named second(), you pass the reference to the object by value. In the method second(), there is a new variable called v, which is a copy of the v in the method first(). Note that the object that v points to is not copied, only the reference to the object is copied, so that v in second() points to the same object as the v in first()!

So if you change anything to the Value object that v in second() points to, it changes also in the Value object that the v in first() points to - because it's the same object.

So if you set v.i in second() to 20, you'll see the change also in the method first().

[ August 29, 2006: Message edited by: Jesper Young ]
[ August 29, 2006: Message edited by: Jesper Young ]
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic