int[] test = {0,1,2,3,4,5};
int[] before = test;
System.out.println(before[2]);
test[2] = 65;
System.out.println(before[2]);
The first System.out prints 2 and it should, but the second prints 65. I have been programming for over a year in this language and as far as I know this is NOT suppose to happen! Any help?
int first = 9;
int second = first;
System.out.println(second);
first = 10;
System.out.println(second);
The code above prints 9 on both lines.
When you do before = test;
, before is just a reference to test
array, NO new array has been created and assigned to test
. So when you look the value of before[i]
you basically look at the value of test[i]
and vice versa. before
is just an alias of test
. That's why in the second print you get 65.
Check this text from Thinking in Java book, it will definitely help you.
Why would you not expect this to happen. You are simply assigning two variables to the same array, and then You are assigning index #2 of that array as 65, so, you should get 65 the next time you print what's on index #2.
see examples at http://download.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
This is normal behavior. If you want to copy an array then you need to copy it.
class ArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
}
}
via http://download.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
For the int's, you are correct they do not reference each other. But when you use an array, they are considered objects, so when you did the before = test
, in memory they are pointing to the same object.