5

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.

Envin
  • 1,463
  • 8
  • 32
  • 69
  • you dont need to return that object – Cris Aug 27 '13 at 12:49
  • no. you need not to return. – AmitG Aug 27 '13 at 12:49
  • 1
    you know you can run it and test .... see if it works – Nimrod007 Aug 27 '13 at 12:49
  • 1
    I don't quite understand the question. You never *have* to return a value unless the method declares a return type. Whether or not you *should* return a value friends on how you want to use the method. Also, even if a method *does* return a value, you can ignore the return value. – Dave Newton Aug 27 '13 at 12:51

4 Answers4

6

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.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
3

You are passing the reference of object1 ,So no need to return it.It changes.

See the code below:

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

And this

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

In both the cases ,After you execute the code object1 updates.

So bottem line is,Not need to return.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
3

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"?

Community
  • 1
  • 1
Ben Dale
  • 2,492
  • 1
  • 14
  • 14
1

It will work, since you are passing the copy of the address location of the object referenced when you dealing with the same object.

JNL
  • 4,683
  • 18
  • 29