Why does the method change passed array's value

ayaz husain :

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.

Andronicus :

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;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31390&siteId=1