To copy an array in Java, you can use the System.arraycopy
method, or you can create a new array and copy the elements from the original array using a loop.
Here is an example of how you can use the System.arraycopy
method to copy an array in Java:
int[] original = {1, 2, 3, 4, 5}; int[] copy = new int[original.length]; System.arraycopy(original, 0, copy, 0, original.length);
In this example, we have an int
array called original
that contains some values. We create a new int
array called copy
with the same length as the original
array, and use the System.arraycopy
method to copy the elements from the original
array to the copy
array.
Here is an example of how you can use a loop to copy an array in Java:
int[] original = {1, 2, 3, 4, 5}; int[] copy = new int[original.length]; for (int i = 0; i < original.length; i++) { copy[i] = original[i]; }
In this example, we have an int
array called original
that contains some values. We create a new int
array called copy
with the same length as the original
array, and use a loop to iterate over the original
array. For each element, we copy the value to the corresponding element in the copy
array.