Reputation: 15
Can someone explain the output of this code? I'm very confused. Before I compiled this code, I thought the output was "4 1 2 3". After compiling the code, it is "4 2 1 0". I'm not sure why so i'm wondering if someone can explain it to me?
public class activity1
{
public static void main(String[]args)
{
//Declare and initialize array
int []list1 = {3,2,1,4};
int [] list2 = {1,2,3};
list2= list1;
list1[0]=0;
list1[1]=1;
list2[2]=2;
//Create for loop
for (int i = list2.length-1; i>=0;i--)
{
System.out.print(list2[i] + " ");//print out the array
}
}
}
Upvotes: 0
Views: 71
Reputation: 513
You can debug and see for yourself what the code is doing at every line:
public static void main(String[] args) {
// Declare and initialize array
int[] list1 = {3, 2, 1, 4};
int[] list2 = {1, 2, 3};
list2 = list1; // list1 = [3, 2, 1, 4] list2 = [3, 2, 1, 4]
list1[0] = 0; // list1 = [0, 2, 1, 4] list2 = [0, 2, 1, 4]
list1[1] = 1; // list1 = [0, 1, 1, 4] list2 = [0, 1, 1, 4]
list2[2] = 2; // list1 = [0, 1, 2, 4] list2 = [0, 1, 2, 4]
// Create for loop
// You are printing list2 in reverse order
for (int i = list2.length - 1; i >= 0; i--) {
System.out.print(list2[i] + " ");// print out the array
}
}
Upvotes: 1
Reputation: 4507
The assignment is just moving a reference to list1 into the list2 variable. So, both variables reference the same array. If you want to copy the array, you will need copy each item from list1 to list 2.
Upvotes: 0
Reputation: 201447
After list2= list1;
there is only one array. {3, 2, 1, 4}
Then, it's modified to {0, 1, 2, 4}
and then it's printed backwards.
Upvotes: 2