0

I could find a lot of information about pass-by-reference and pass-by-value about java method arguments but not of the following kind where a method1 argument is modified in another method2 and simultaneously set to itself in method1.

public class TestQDoc {
    public  QDoc method1(QDoc doc) {
        doc = (QDoc) method2(doc);
        return doc;
    }

    public QDoc method2(QDoc doc) {
        doc.x = 100;
        return doc;
    }

    public static void main(String [] args) {
        QDoc doc = new QDoc();
        doc.x=200;
        TestQDoc tq = new TestQDoc();
        doc=tq.method1(doc);
        System.out.println(doc.x);
    }

    static class QDoc {
        public Integer x;
    }
}

The above code is printing 100 as expected. I am not sure if the method arguments are passed by reference or passed by value. Also, is there any possibility that method1 fails to return the modified doc in method2?

17slim
  • 1,233
  • 1
  • 16
  • 21
  • The method is changing something inside the object. In addition, you are returning the object and reassigning the variable at each point (to the same reference in this case), so even if a new object had been created, you would have been operating on that new object. It is unclear what you are really asking. – Mark Rotteveel Aug 05 '19 at 15:34
  • Please format your code properly. In its current state it's a little hard to read. – MC Emperor Aug 05 '19 at 15:50

1 Answers1

0

Java is always pass-by-value. Unfortunately, when we pass the value of an object, we are passing the reference to it.

You are passing an object and modifying its internal field and the reference to the object stays the same.

Check this thread: Is Java "pass-by-reference" or "pass-by-value"?