Java Copy Arrays
In Java, sometimes we need to copy an array into another array. This is useful when we want to create a duplicate of an existing array without modifying the original one.
In this blog, we will cover:
Different ways to copy an array
- Using Loop for copying
- Using
arraycopy()
method - Using
clone()
method - Using
Arrays.copyOf()
method - Using
Arrays.copyOfRange()
method
Example programs with expected outputs
1. Copying an Array Using a Loop#
The most basic way to copy an array is to use a loop.
Example: Copying an array using a loop#
Output:#
Best For: Small-sized arrays when performance is not a major concern.
2. Copying an Array Using System.arraycopy()
#
The System.arraycopy()
method is an efficient way to copy an array in Java.
Syntax:#
- sourceArray → The original array
- sourcePosition → The starting index to copy from
- destinationArray → The new array where values will be copied
- destinationPosition → The index where copying starts in the destination array
- length → Number of elements to copy
Example: Using System.arraycopy()
#
Output:#
Best For: Fast copying when working with large arrays.
3. Copying an Array Using clone()
#
The clone()
method is used to create a shallow copy of an array. It works only for one-dimensional arrays.
Example: Using clone()
#
Output:#
Best For: Quick duplication of arrays when dealing with primitive types.
Limitation: If the array contains objects, clone()
performs shallow copying, meaning it only copies object references, not the actual objects.
4. Copying an Array Using Arrays.copyOf()
#
The Arrays.copyOf()
method is a simple way to copy an array while also allowing us to change its size.
Example: Using Arrays.copyOf()
#
Expected Output:#
Best For: Copying an entire array or resizing an array during copying.
5. Copying a Portion of an Array Using Arrays.copyOfRange()
#
The Arrays.copyOfRange()
method is useful when we need to copy only a specific range of elements.
Syntax:#
- fromIndex → Start index (inclusive)
- toIndex → End index (exclusive)
Example: Copying a Range of an Array#
Expected Output:#
Best For: Extracting a sub-array from a larger array.
Choosing the Right Method to Copy an Array#
Method | When to Use? |
---|---|
Loop Method | For small arrays, simple approach |
System.arraycopy() | For fast, efficient copying |
clone() | For shallow copy of one-dimensional arrays |
Arrays.copyOf() | When resizing or copying the full array |
Arrays.copyOfRange() | When copying a portion of an array |
Conclusion#
In this blog, we learned:
- How to copy arrays using loops
- How to use
System.arraycopy()
for fast copying - How
clone()
creates a duplicate of an array - How to use
Arrays.copyOf()
andArrays.copyOfRange()
- When to use each method
Each method has its advantages, and the best choice depends on the size of the array and performance considerations.