开发者

Java array - from test

In my Java test was the next question:

there is the next method:

public void changer(int[] x, int y) {

    x[y] = x[y] +3;
    开发者_运维知识库y = y * 2;
}

We have array named a, with the values:

2,4,0,1,-6,3,8,7,5

if b = 3

what will be a and b values after the next call:

changer(a,b);

My answer was: b = 6

a = 2,4,0,4,-6,3,8,7,5

I've tested it on BlueJ and got the same answer, but the tester wrote: wrong !

what do you say?


You are right about array values, but wrong about b value.

When you call a method, java passes everything by value, that mean that changing y only changes the value locally, and the change is not reflected on b.

However, when passing arrays and objects, a value representing a pointer to the array is passed. That means that x = new int[8] does not alter a at all, since as it happens for y the change is not reflected to a. However, changing array members or object properties works as you expected, cause a and x both point to the same array in memory.


from the scope where changer is called b doesn't change, because Java is pass by value and b is a primitive. So b would still be 3 after the method call. The statement in changer:

y = y * 2

after changing the value in the array effectively does nothing.

Your answer for a is correct.


b should still be 3. Passing an integer passes it "by value", so it is essentially a copy of b that goes into the changer method.


B won't be changed because it is a primitive passed as a method parameter. In that case a local copy is made, which is in this case multiplied by two. The original b will not be affected by this though. The array is changed because arrays (even arrays of primitives) are Objects in Java, so the reference to the array is passed into the method and changes to the array (via the reference) are reflected in the one and only array - no copy is made in this case.


You're confusing values and references, and thinking of the y value as if it's a reference.

The first line x[y] = x[y] +3; sets the value of the yth element of the array. The following line y = y * 2; changes the value of the parameter but doesn't alter the array setting.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜