underdog underdog - 4 months ago 8
Java Question

Passing an object as a parameter in Java

There is a scenario

Say I have a class

People
& a utility class
PeopleUtil
with a method
computeTotalNumberOfPeople


In a separate class say
EvaluatePeople
where I have code

People people = new People();
people.setValue(10);
people.setX(45);
PeopleUtil.computeTotalNumberOfPeople(people);
this.persistPeople(people);


In the
computeTotalNumberOfPeople
method

public void computeTotalNumberOfPeople(People people){
//logic for computing total no of people & then
int totalPeople = certainIntValue;
// I can return the totalPeople value from this method but I am not doing it just for the sake of this scenario
people.setTotalNumberOfPeople(totalPeople);
}


When I look at the People object in the db row I see the
totalNumberOfPeople
value persisted. Which is actually fine.

My question is, I am a little confused about it, shouldn't
computeTotalNumberOfPeople
method return the people object, which has an extra set value, to the method caller code & then that object should be passed to the peristPeople method as an argument?

I hope you understand what I mean, it doesn't seem right someway

Answer

Objects are mutable – they can be changed.

So when you call people.setTotalNumberOfPeople(totalPeople), you are setting the totalNumberOfPeople variable (or whatever it's called inside the People class) to totalPeople for the people object.

When you exit the computeTotalNumberOfPeople method, the object is still the same one that was modified – the changes from the method persist.

One way to think about it is passing a reference to people. When you call computeTotalNumberOfPeople(people), you are passing a reference to people. When people is modified, you modifying the same location in memory, and so the changes persist.