I am confused in the following:
In C++ we can pass a parameter to a function by reference (having declared it as a pointer or reference variable) and if we modify it inside the function, the changes are reflected to the caller when the function returns.
This is not happening in java and I am not sure I understand why.
E.g. this is a method from an object X
public boolean aMethod(int id, myClass aClass)
{
//do some logic
aClass = new MyClass();
//configure argument object aClass
return true;
}
In the calling code:
//some code processing
myClass obj = null;
if(X.aMethod(2,obj))
{
obj.methodA();//start using the object
}
I use it in C++, i.e. to return a result that notifies that the function parameter can be used, but in java this does not work.
I enter the if(X.aMethod(2,obj)) branch but the obj is null. Why is it null?
Haven’t I assigned a memory address from the heap using new inside the method aMethod(int id, myClass aClass)? Am I not passing the “address” of obj in the function?
I was expecting to have the obj properly constructed and usable in the calling code. Have I misunderstood something concerning memory in java?
Java passes everything by value – including references.
What this means is that if you pass an object, you can modify properties of that object, and they will persist after you return, but you can’t replace the object in its entirety with a completely new object, because you can’t actually modify the reference – only what the reference points to.
Before your
aClass =line:After your
aClass =line:The key thing to notice here is that
aClassdoesn’t point toobj– it points to<foo>. You’re not passing the address ofobj, you’re passing the address of whatobjpoints to. Thus, when you change whataClasspoints to, that doesn’t touchobj.As an alternative way of thinking about it:
In Java,
is equivalent to C++,
Thus when you pass
footo a function, you’re not passing the address offoo– you’re passing the address of the allocated object. Java doesn’t have the&-operator style pass-by-reference that C/C++ do.