Reputation: 2402
While reviewing some java code, I've run into a piece of code as this:
Integer initialQ = someObject.getInitialQ();
Integer finalQ = null;
BigDecimal factor = calculateFactor(initialQ, finalQ);
if (finalQ.compareTo(initialQ) != 0){
//do something
}
finalQ
is modified in the method calculateFactor.
Eclipse gives me a "Null pointer access: The variable idUnidadFinal can only be null at this location" warning on if (finalQ...)
. I understand that since we need to get factor
returned from the method, the only way to modify finalQ
is to pass it as reference. But, is this the correct, accepted way of doing it?
The only alternative I can think of is to design a new class which has finalQ
and factor
as fields, but looks unnecessarily complicated.
Upvotes: 0
Views: 976
Reputation: 2257
There is no such thing called pass by reference in java, it is a confusing term.
When you pass a object to another function, what is passed through is the value of the reference. In the method, a local copy of reference is created and point to the same memory address. So usually if you pass and non-null variable and modify it in a separate method, the original object is changed as well because the original one and the method local copy are pointing to the same memory address, but if you assign a new instance to the method local copy then subsequent change to the local copy has nothing to do with the original one.
In your case, I guess you assign an non-null instance to finalQ in calculateFactor, which makes the local copy of finalQ point to another memory address and leave the original finalQ along.
So if you want to modify a object passed into a method, you can only change it itself but not assign it with another reference. If the initially passed in object is null and you are expecting the change against original object, you must return the changed object back.
Upvotes: 2
Reputation: 2753
This is not pass by reference. There is a new object created in the function it is passed to. The value of finalQ
can only be null. You need to return that object back if you want to change the value or make finalQ
global.
Upvotes: 4