1

Why does this code return 4 4 rather than 4 1?

I traced the new values[k] to be 4 through the for-loop, but I understand that int[] numbers was copied to the original int[] values array, so did the int[] numbers change WITH int[] values through the for-loop?

Is this a rule I'm not aware of?

int[] values = { 1, 3, 1, 3, 1 };
int[] numbers = values;
for (int k = 0; k < values.length; k++)
{
  values[k] = k * 2;
}
System.out.print(values[2]);
System.out.print(" " + numbers[2]);
GhostCat
  • 137,827
  • 25
  • 176
  • 248
Saksham
  • 15
  • 2
  • 1
    Before post on stackoverflow, DEBUG your code. If you had stopped your cose at the end you should had seen that the two arrays are equals. – betontalpfa May 06 '17 at 17:41

3 Answers3

0

Because in Java, arrays are references. Basically, values is not the array itself, but something which "refers" or "points to" an array. The reference and the array itself are disconnected.

When you do numbers = values, you don't create a copy of values and put in a new array called numbers, but rather you make numbers point to the same thing that values points to. This means that whenever you change one of them, you will change both. See Make copy of array Java for how to make a copy of values.

Community
  • 1
  • 1
Paul92
  • 8,827
  • 1
  • 23
  • 37
0

Because int[] numbers = values; does not copy the array values (just assigns the same reference to numbers). You can use Arrays.copyOf(int[], int) like

int[] numbers = Arrays.copyOf(values, values.length);

for the behavior you expected.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

As array is not a primitive type, when you assign an array variable the another array , the reference is copied. See this answer to know more on this.

In your case , the numbers variable is pointing to same memory location as of values. And hence the answer is 4 4.

Community
  • 1
  • 1
Shailesh Pratapwar
  • 4,054
  • 3
  • 35
  • 46