package javaapplication8;
public class Main {
public static void main(String[] args) {
int[] list1 = {1, 2, 3,4};
int[] list2 = {5, 6, 7,8};
for (int i = 0; i < list2.length; i++){
System.out.print(list2[i] + " ");
}
System.out.println("");
list2 = list1;
for (int i = 0; i < list2.length; i++){
System.out.print(list2[i] + " ");
}
System.out.println("");
//Change list1
list1[0] = -1;
//Change list2
list2[3] = -4;
//List1 output
for (int i = 0; i < list1.length; i++){
System.out.print(list1[i] + " ");
}
System.out.println("");
//List2 output
for (int i = 0; i < list2.length; i++){
System.out.print(list2[i] + " ");
}
System.out.println("");
//Set list1
list1 = new int[2];
list1[0] = 100;
list1[1] = 99;
//List1 output
for (int i = 0; i < list1.length; i++){
System.out.print(list1[i] + " ");
}
System.out.println("");
//List2 output
for (int i = 0; i < list2.length; i++){
System.out.print(list2[i] + " ");
}
System.out.println("");
}
}
run:
5 6 7 8
1 2 3 4
-1 2 3 -4
-1 2 3 -4
100 99
-1 2 3 -4
List 1 and List 2 are pointing to same array object after you do List2 = list1;
so doing List2[3] = -4; actually does it for array object that earlier was pointed by List1.
and remember the array object that was earlier related to List2 now stands for garbage collection.
So earlier when u did List1 = x and List2 = y there were two array objects in the memory pointed out by list1 and list2 variables. However after doing list2 = list1 u made both variables point to x array and the other array is free now and java will need to recollect this memory sometime and hence whatever changes ur doing is done to object x rather than y