underdog underdog - 1 year ago 73
Java Question

Passing an object as a parameter in Java

There is a scenario

Say I have a class

& a utility class
with a method

In a separate class say
where I have code

People people = new People();

In the

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

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

My question is, I am a little confused about it, shouldn't
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download