Search code examples
javaarraysoopcall-by-value

Call by reference-or- Call by value


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.print(b.size + " ");
    }

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

What the result? 
A. 4 4 
B. 5 4 
C. 6 4 
D. 4 5 
E. 5 5 
F. Compilation fails 

The answer is A

I am having hard time trying to understand the results of this code. Can anyone explain the results to me?


Solution

  • Here is some explanations -

    1. First of all you have create a Box in main() class -

     Box b1 = new Box(5);  
    

    2. Then send b1 to go() method -

       Box[] ba = go(b1, new Bo(6));
    

    Now b1.size is 5

    3. In method go() you are setting b1.size to 4 using the assignment statement -

    b1.size = 4;  
    

    4. Now you are creating a new Box array ma -

    Box[] ma = { b2, b1 };  
    

    In this array the first element is b2 and b2.size is 6. See point 2.

    5. Then you return ma and at point 2 the returned array ma is assigned with ba. Now the first element of the array is 6 and the second element of the array is 4.

    6. ba[0] = b1; - this statement sets the first element of ba[0] to b1. Note at point 2 b1.size was set to 4.

    Now ba[0].size is 4
    and ba[1].size is 4

    And that's why the output is 4 4