Value of the array "r" gets updated to 2?

74 views Asked by At

"Why does the value of r change to 2 2 while it's re that I am changing, that too in another function?"

class Ideone {// main
    public static void main(String[] args) throws java.lang.Exception {
        int[] r = new int[2];
        for (int i = 0; i < r.length; i++)
            System.out.println(r[i]);
        int[] catch1 = doesThisWork(1, 2, r);
        // the value of r changes!?
        for (int i = 0; i < r.length; i++)
            System.out.println(r[i]);
    }// doesthisWork

    public static int[] doesThisWork(int a, int b, int[] re) {
        for (int i = 0; i < re.length; i++) {
            re[i] = b;
        }
        return re;
    }
}
3

There are 3 answers

0
Eran On

doesThisWork accepts a reference to the r array, which means it is able to change the contents of that array. While assigning a new value to the re variable inside the method wouldn't change the value of r when the method returns (since Java is a pass by value language), changing the state of the object referred by re (which is an array in your case), affects the state of r, since r and re refer to the same object.

0
Aniket Thakur On

Java is pass by value of the reference!

So when you do

public static int[] doesThisWork(int a, int b, int[] re) {
    for (int i = 0; i < re.length; i++) {
        re[i] = b;
    }
    return re;
}

your int[] re is referring to actual array instance pointed by int[] r and any change made will be reflected to original array.

0
Mohammad Ali Saatchi On

in this code when give int[] r as an entry to doesThisWork(int a, int b, int[] re), be careful because java hold the pointer to r and if any changes happen to re It means the pointer also has to change the reference (it is call by reference). in order to solve this problem use a tmp array:

    int[] tmp = re
    for (int i = 0; i < tmp.length; i++) {
        tmp[i] = b;
    }
    return tmp;