Search code examples
javastatic-methodspass-by-referencecall-by-value

Call by reference or Call by value


Could somebody please explain how this program is executed?

Here is the code whose output I just can't quite seem to get it:

    class Box {
        int size;
        Box (int s) {
           size = s;
        }
    }
    public class Laser {
        public static void main(String[] args) {
            Box b1 = new Box(5);
            Box[] ba = go(b1, new Box(6));
            ba[0] = b1;
            for(Box b : ba)
                System.out.println(b.size + " ");
        }

        static Box[] go (Box b1, Box b2) {
            b1.size = 4;
            Box[] ma = {b2, b1};
            return ma;
        }
    }

The actual output when I run this is 4, 4. But according to my understanding this should be 5, 4. Can anyone please help understand how this is being executed?


Solution

  • When you pass an object as a parameter, you're actually passing a copy of a reference to it. That is, if you modify the parameter object inside the method, the object will retain those modifications when that method returns, which is why you see b1 retaining the size = 4 assignment after go returns.