In Java, we can copy one array into another. There are several techniques you can use to copy arrays in Java. Let's take an example,
Output for the above code block will be 1, 2, 3, 4, 5, 6. In the above example, we have used the assignment operator (=) to copy an array named numbers to another array named positiveNumbers. This technique is the easiest one and it works as well. However, there is a problem with this technique. If we change elements of one array, corresponding elements of the other arrays also change. For example,
Output for the above program can look like -1, 2, 3, 4, 5, 6. Here, we can see that we have changed one value of the numbers array. When we print the positiveNumbers array, we can see that the same value is also changed. It's because both arrays refer to the same array object. This is because of the shallow copy. To learn more about shallow copy, visit shallow copy. Now, to make new array objects while copying the arrays, we need deep copy rather than a shallow copy.