Following program output
In second v.i:15
In first v.i:20
why its not 15 in both cases.Object of Value is passed and then object reference is changed in the Second method.Second method its 15 as it should be and seems like in First method it should also be 15
public class Test {
/**
* @param args
*/
class Value{
public int i = 15;
}
public static void main(String[] args) {
Test t = new Test();
t.first();
}
public void first(){
Value v = new Value();
v.i = 25;
second(v);
System.out.println("In First v.i:" + v.i);
}
public void second(Value v){
v.i = 20;
Value val = new Value();
v = val;
System.out.println("In second v.i:" + v.i);
}
}
Java method implementations are
call by[reference to, in case of objects,]valuebut not exactly acall by reference.You are passing an object
Value vmeans an in-line, method scope variablevis referring to the objectvcreated in methodfirst(). That means any modifications to the same object, referred byv, will also reflect at calling end. But, in yoursecondmethod, you are creating a fresh object forValuebut pointing to the method scope variablev. This new objects memory location is not the same as that of passed in method parameter. To identify the difference, check thehashCodeof the objects created using their reference variables.And hence changing the instance variables of
vin methodsecondwill not be returned to the caller of the method, unless the method is returning the altered object. Your method returns avoidhere.Programmers, most of the time, get confused with the same reference names used in caller and called methods.
Look at the following example to understand the difference. I have included a
third' and afourth` methods, to explain it further.When you run the above example, you may see an output as below:
If you really want to hold the changes made to an object
instanceVariableVin a called method, sayfifth(), the other possibility is to declarevas instance variable.Following example will explain the differences.
When you run with the above extended example, you may see an output as below:
Hope this helps you.
Other references: