The issue with your code is that the loop counter is running in the backward direction because of transfer--
and when it's reaching -1
, trying to access array2[-1]
is throwing the ArrayIndexOutOfBoundsException
because the lowest index in an array is 0
.
By the way, you can transfer elements from one array to another using System.arraycopy
easily as follows:
import java.util.Arrays;
class Main {
public static void main(String[] args) {
int[] array1 = { 1, 2, 3, 4, 5, 6 };
int[] array2 = { 7, 8, 9, 10, 11, 12 };
System.out.println(Arrays.toString(array1));
System.out.println(Arrays.toString(array2));
System.arraycopy(array1, 2, array2, 2, 3);
System.out.println(Arrays.toString(array2));
}
}
Output:
[1, 2, 3, 4, 5, 6]
[7, 8, 9, 10, 11, 12]
[7, 8, 3, 4, 5, 12]
Update:
From your comment, I understand that you wanted to copy elements from array1
to array2
in reverse order. Given below is the code for the same:
class Main {
public static void main(String[] args) {
int[] array1 = {5,8,11,1,6};
int[] array2 = new int[5];
// Copy elements from array1 to array2 in reverse order
for(int i=0;i<array1.length;i++) {
array2[i]=array1[array1.length-1-i];
}
//Print elements of array2
for(int n:array2) {
System.out.print(n+" ");
}
}
}