ayaz husain
ayaz husain

Reputation: 41

Why does the method change passed array's value

I am making changes in a local variable and returning it. I think it should print 12 at line no 9.

public class HackerEarth {

    int a[]= {3,4,5};
    int b[]=foo(a);

    void display() {
        System.out.println(a[0]+a[1]+a[2]+ " "); //line no 9
        System.out.println(b[0]+b[1]+b[2]+ " ");
    }

    public static void main(String[] args) {
        HackerEarth he=new HackerEarth();
        he.display();
    }
    private int[] foo(int[] a2) {
        int b[]=a2;
        b[1]=7;
        return b;
    }
}

Any suggestion would be appreciated.

Upvotes: 0

Views: 75

Answers (3)

Adnan
Adnan

Reputation: 496

instead of assigning reference of array a int b[] = a2; to array b you can copuy the values of array a to b :

private int[] foo(int[] a2) {
    int[] b = Arrays.copyOf(a2,a2.length);
    b[1]=7;
    return b;
}

Output

 12
 15

Upvotes: 1

Andronicus
Andronicus

Reputation: 26046

You're using the reference to the first array to overwrite it's value in foo method. To create another array based on values of the passed ones, consider using Arrays.copyOf:

private int[] foo(int[] a2) {
    int b[] = Arrays.copyOf(a2, a2.length);
    b[1]=7;
    return b;
}

Upvotes: 1

WJS
WJS

Reputation: 40034

Because you are changing the second value in the array to 7. You are doing this in the method.

    private int[] foo(int[] a2) {
        int b[] = a2; // <-- copying the array reference.
        b[1] = 7; // so changing the second value here.
        return b;
    }

Upvotes: 1

Related Questions