+ 4
Can anuone explain me this program
this is a program of java of call by value and my doubt is why am i getting the same answer even after callong the method to it.. https://code.sololearn.com/ctFuU2T301YO/?ref=app
3 Answers
+ 3
hi @Petja Boigk thanks for answering my question, i would really appreciate if you can compile my attached program with the above question and tell me if thats correct or is there any changes that need to be made. plz reply asap
+ 1
because in primitive types the value is directly stored into variable. object variables are storing the reference. so what happens you call the method by value with the actual numbers but not the reference of the variable. if you change a value there the original will not be influenced.
reassign objects doesn't work too.
e.g. here the same applies.
void func (Object a) {
a= new XyzObject ();
}
that's fundamental different in c, in which you can give the actual reference of the variable (not the object!) itself.
+ 1
well if you want to "see" the changes, you have to either return the result (e.g. encapsulate into a tuple type which is easily implemented) or encapsulate the variable you are passing itself into a tuple.
e.g.
class MyTuple {
int x, y;
//getter setter constructor
...
}
e.g. Method 1
MyTuple callFunc (x, y) {
return new MyTuple(xnew,ynew);
}
...
x=...
y=...
MyTuple tuple = callFunc (x,y);
x=tuple.getX ();
y=tuple.getY ();
method 2
void callFunc (MyTuple tuple) {
tuple.setX (xnew);
tuple.setY (ynew);
}
...
MyTuple tuple=new MyTuple (x, y);
callFunc (tuple);