I came across two examples from my notes regarding copying arrays.
The first example below indicates that this is not a way to copy an array. But, when I tried to run the code, it managed to copy all the values ββfrom array1 to array2.
int []array1={2,4,6,8,10};
int []array2=array1;
for(int x:array2){
System.out.println(x);
}
The second example shows the correct way to copy an array.
int[] firstArray = {5, 10, 15, 20, 25 };
int[] secondArray = new int[5];
for (int i = 0; i < firstArray.length; i++)
secondArray[i] = firstArray[i];
My question is whether these 2 examples are suitable for coding or the preferred example 2. If you were my teacher, I should have applied example 1. Will I be given less sign compared to the method of example 2 or just the same?
source
share