Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to return an object from a method if I'm modifying it?

Tags:

java

Say I have code

if(some statement){
   object1.setSomeField("abc");
}

Could I do this?

    public void methodToSetField(SomeObject object1){
       //provide some logic for setting
       object1.setSomeField("abc")
    }

   if(some statement){
      this.methodToSetField(object1);
   }

Now my question is, if I want to replace the first piece of code, with the method do I need to return object1 or is it enough to set it.

like image 600
Envin Avatar asked Aug 27 '13 12:08

Envin


2 Answers

No you don't have to , as you are working on the same memory object. So the calling code, if uses the values after calling your method, it should see the updates.

like image 121
Juned Ahsan Avatar answered Oct 22 '22 05:10

Juned Ahsan


That is fine to do. In java, when you pass in an object, you don't actually pass in the "object" but rather the reference (or pointer) to the object.

Any modifications you make will directly alter the object you've passed in as long as you don't do something like:

SomeObject someObject = new SomeObject();

EDIT: Is Java "pass-by-reference" or "pass-by-value"?

like image 30
Ben Dale Avatar answered Oct 22 '22 06:10

Ben Dale