How to assign a value from one Java array to another array?
To assign one Java array to another, you can either use the clone() method of the array or utilize the System.arraycopy() method.
- Use the clone() method:
int[] array1 = {1, 2, 3, 4, 5};
int[] array2 = array1.clone();
In this example, a new array array2 is created by calling the clone() method on the array1 array. The elements in array2 are the same as in array1.
- Use the System.arraycopy() method:
int[] array1 = {1, 2, 3, 4, 5};
int[] array2 = new int[array1.length];
System.arraycopy(array1, 0, array2, 0, array1.length);
In this example, a new array, array2, is first created with the same length as array1. Then, the elements of array1 are copied to array2 using the System.arraycopy() method.
You can assign one Java array to another array using any method.