0% found this document useful (0 votes)
5 views8 pages

Java Array Copy Techniques Explained

This tutorial explains various methods to copy arrays in Java, including using the assignment operator, loops, the arraycopy() method, and the copyOfRange() method. It highlights the difference between shallow and deep copies, demonstrating how changes in one array can affect another when using shallow copies. Additionally, it covers copying two-dimensional arrays using both loops and the arraycopy() method.

Uploaded by

David
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views8 pages

Java Array Copy Techniques Explained

This tutorial explains various methods to copy arrays in Java, including using the assignment operator, loops, the arraycopy() method, and the copyOfRange() method. It highlights the difference between shallow and deep copies, demonstrating how changes in one array can affect another when using shallow copies. Additionally, it covers copying two-dimensional arrays using both loops and the arraycopy() method.

Uploaded by

David
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Copy Arrays

In this tutorial, you will learn about diifferent ways you can use to copy arrays
(both one dimensional and two-dimensional) in Java with the help of
examples.

In Java, we can copy one array into another. There are several techniques you
can use to copy arrays in Java.

1. Copying Arrays Using Assignment Operator


Let's take an example,

class Main {
public static void main(String[] args) {

int [] numbers = {1, 2, 3, 4, 5, 6};


int [] positiveNumbers = numbers; // copying arrays

for (int number: positiveNumbers) {


[Link](number + ", ");
}
}
}
Run Code

Output:

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,
class Main {
public static void main(String[] args) {

int [] numbers = {1, 2, 3, 4, 5, 6};


int [] positiveNumbers = numbers; // copying arrays

// change value of first array


numbers[0] = -1;

// printing the second array


for (int number: positiveNumbers) {
[Link](number + ", ");
}
}
}
Run Code

Output:

-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.

2. Using Looping Construct to Copy Arrays


Let's take an example:

import [Link];

class Main {
public static void main(String[] args) {
int [] source = {1, 2, 3, 4, 5, 6};
int [] destination = new int[6];

// iterate and copy elements from source to destination


for (int i = 0; i < [Link]; ++i) {
destination[i] = source[i];
}

// converting array to string


[Link]([Link](destination));
}
}
Run Code

Output:

[1, 2, 3, 4, 5, 6]

In the above example, we have used the for loop to iterate through each
element of the source array. In each iteration, we are copying elements from
the source array to the destination array.
Here, the source and destination array refer to different objects (deep copy).
Hence, if elements of one array are changed, corresponding elements of
another array is unchanged.

Notice the statement,

[Link]([Link](destination));

Here, the toString() method is used to convert an array into a string. To learn
more, visit the toString() method (official Java documentation).

3. Copying Arrays Using arraycopy() method


In Java, the System class contains a method named arraycopy() to copy arrays.
This method is a better approach to copy arrays than the above two.
The arraycopy() method allows you to copy a specified portion of the source
array to the destination array. For example,

arraycopy(Object src, int srcPos,Object dest, int destPos, int length)

Here,

• src - source array you want to copy


• srcPos - starting position (index) in the source array
• dest - destination array where elements will be copied from the source
• destPos - starting position (index) in the destination array
• length - number of elements to copy
Let's take an example:

// To use [Link]() method


import [Link];

class Main {
public static void main(String[] args) {
int[] n1 = {2, 3, 12, 4, 12, -2};

int[] n3 = new int[5];

// Creating n2 array of having length of n1 array


int[] n2 = new int[[Link]];

// copying entire n1 array to n2


[Link](n1, 0, n2, 0, [Link]);
[Link]("n2 = " + [Link](n2));

// copying elements from index 2 on n1 array


// copying element to index 1 of n3 array
// 2 elements will be copied
[Link](n1, 2, n3, 1, 2);
[Link]("n3 = " + [Link](n3));
}
}
Run Code

Output:

n2 = [2, 3, 12, 4, 12, -2]


n3 = [0, 12, 4, 0, 0]

In the above example, we have used the arraycopy() method,


• [Link](n1, 0, n2, 0, [Link]) - entire elements from the n1 array
are copied to n2 array
• [Link](n1, 2, n3, 1, 2) - 2 elements of the n1 array starting from
index 2 are copied to the index starting from 1 of the n3 array
As you can see, the default initial value of elements of an int type array is 0.

4. Copying Arrays Using copyOfRange() method


We can also use the copyOfRange() method defined in Java Arrays class to
copy arrays. For example,
// To use toString() and copyOfRange() method
import [Link];

class ArraysCopy {
public static void main(String[] args) {

int[] source = {2, 3, 12, 4, 12, -2};

// copying entire source array to destination


int[] destination1 = [Link](source, 0, [Link]);
[Link]("destination1 = " + [Link](destination1));

// copying from index 2 to 5 (5 is not included)


int[] destination2 = [Link](source, 2, 5);
[Link]("destination2 = " + [Link](destination2));
}
}
Run Code

Output

destination1 = [2, 3, 12, 4, 12, -2]


destination2 = [12, 4, 12]

In the above example, notice the line,


int[] destination1 = [Link](source, 0, [Link]);

Here, we can see that we are creating the destination1 array and copying
the source array to it at the same time. We are not creating
the destination1 array before calling the copyOfRange() method. To learn more
about the method, visit Java copyOfRange.

5. Copying 2d Arrays Using Loop


Similar to the single-dimensional array, we can also copy the 2-dimensional
array using the for loop. For example,
import [Link];

class Main {
public static void main(String[] args) {

int[][] source = {
{1, 2, 3, 4},
{5, 6},
{0, 2, 42, -4, 5}
};

int[][] destination = new int[[Link]][];

for (int i = 0; i < [Link]; ++i) {

// allocating space for each row of destination array


destination[i] = new int[source[i].length];

for (int j = 0; j < destination[i].length; ++j) {


destination[i][j] = source[i][j];
}
}

// displaying destination array


[Link]([Link](destination));

}
}
Run Code

Output:

[[1, 2, 3, 4], [5, 6], [0, 2, 42, -4, 5]]

In the above program, notice the line,

[Link]([Link](destination);

Here, the deepToString() method is used to provide a better representation of


the 2-dimensional array. To learn more, visit Java deepToString().

Copying 2d Arrays using arraycopy()


To make the above code more simpler, we can replace the inner loop
with [Link]() as in the case of a single-dimensional array. For
example,
import [Link];

class Main {
public static void main(String[] args) {

int[][] source = {
{1, 2, 3, 4},
{5, 6},
{0, 2, 42, -4, 5}
};

int[][] destination = new int[[Link]][];

for (int i = 0; i < [Link]; ++i) {

// allocating space for each row of destination array


destination[i] = new int[source[i].length];
[Link](source[i], 0, destination[i], 0,
destination[i].length);
}
// displaying destination array
[Link]([Link](destination));
}
}
Run Code

Output:

[[1, 2, 3, 4], [5, 6], [0, 2, 42, -4, 5]]

Here, we can see that we get the same output by replacing the inner for loop
with the arraycopy() method.

Common questions

Powered by AI

Using a loop to copy arrays in Java involves iterating through each element of the source array and individually assigning it to the destination array. This method offers precision and control over the copying process but can be less efficient in terms of performance due to the overhead of repeated loop iterations. On the other hand, the arraycopy() method is optimized for performance, particularly for large arrays, since it uses system-level native operations to copy sections of memory directly, thus reducing the overhead of individual assignments .

The arraycopy() method in Java is part of the System class and is used to copy a specified portion of the source array to the destination array with defined start and end positions. This allows for copying specific parts of arrays and is efficient for performance . In contrast, the copyOfRange() method, found in the Arrays class, allows copying a range from the source array to a new array but does not require manual creation of the destination array beforehand. It is more flexible in everyday use when copying entire subarrays as it simplifies memory allocation handling .

The copyOfRange() method simplifies the process of copying an array in Java by enabling the direct creation and copying of a specified range from a source array into a new array in a single method call. While manual iteration requires explicit loop constructs to allocate memory and copy each element individually, copyOfRange() handles memory allocation and copying internally. This streamlines code, minimizes errors, and enhances readability without manually managing the copying process .

When a shallow copy technique is employed in Java, such as using the assignment operator to duplicate an array, both the original and the copied array references point to the same memory location. Consequently, any modification to array elements through either reference will affect both references, leading to undesirable side effects if the arrays were intended to be managed independently. This may introduce bugs due to shared state which can be difficult to track and rectify .

Copying only a portion of an array using the arraycopy() method in Java is useful in scenarios where memory optimization or performance considerations are crucial. For instance, when handling large data sets, copying only required segments minimizes memory usage and reduces processing time. It also allows efficient manipulation of data subfields, such as when processing sections of image or sound byte arrays in multimedia applications, effectively segmenting data without duplicating the entire array .

Copying arrays using the assignment operator in Java is advantageous for its simplicity and ease of use, as it only requires assigning one array reference to another. However, the major disadvantage is that it leads to a shallow copy, meaning both variables point to the same array object. Consequently, if elements in one array are modified, the changes reflect in the other array as well, which can lead to unintended side effects .

The deepToString() method in Java enhances the display of multi-dimensional arrays by providing a complete and nested string representation of the array's entire structure. This method recursively processes and formats each dimension of a multi-dimensional array, making it comprehensible and easy to read in output, which is otherwise challenging with the default toString() method that only provides a reference for non-primitive array types .

The advantages of using a deep copy over a shallow copy when dealing with arrays in Java include ensuring data encapsulation and integrity by duplicating the actual array elements rather than references. This prevents unintended side effects, where modifications to one array are reflected in another, allowing each array to be managed independently. Deep copies are crucial when arrays need to maintain their own states, such as in concurrency, avoiding synchronization issues and preserving original data consistency .

The copyOfRange() method would be preferred when copying a specific range of an array into a standalone array is required, and simplicity and code neatness are priorities over performance, such as in smaller applications or educational scenarios. While it may not offer the granular control and optimization that arraycopy() provides for very large datasets, copyOfRange() facilitates quick and clear code for straightforward segments, enhancing readability without additional memory management concerns .

Using a manual loop to copy elements of a two-dimensional array in Java involves constructing separate loops for each dimension, which can become cumbersome and error-prone, particularly as array complexity increases. This approach is less efficient than using System.arraycopy(), which can perform a more optimized copy operation at the system level without the need for explicit loop constructs. While loops provide detailed control over the process, they add complexity and the potential for mistakes in memory allocation and indexing, which arraycopy() manages more seamlessly with less code .

You might also like