ow to Merge Two Arrays in Java

Merging two arrays is a common operation in Java and introduces one of the language's most useful built-in methods: System.arraycopy(). While manually copying elements works perfectly, Java provides highly optimized alternatives that are faster and more concise. This guide covers manual merging, System.arraycopy(), Java Streams, and the classic two-pointer algorithm used to merge two already sorted arrays.


Problem Statement

Given two arrays:

 
{1, 2, 3}

{4, 5, 6}
 

Merge them into a single array:

Advertisement
 
{1, 2, 3, 4, 5, 6}
 

Method 1: Manual Loop Merge

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

int[] merged = new int[array1.length + array2.length];

int index = 0;

for (int num : array1) {
    merged[index++] = num;
}

for (int num : array2) {
    merged[index++] = num;
}

System.out.println(java.util.Arrays.toString(merged));
 

This approach is straightforward and easy to understand, making it ideal for learning the fundamentals.


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

int[] merged = new int[array1.length + array2.length];

System.arraycopy(array1, 0, merged, 0, array1.length);

System.arraycopy(array2, 0, merged, array1.length, array2.length);

System.out.println(java.util.Arrays.toString(merged));
 

System.arraycopy() copies elements directly in memory using a native JVM implementation, making it faster than manual loops for large arrays.

Its syntax is:

 
System.arraycopy(source,
                 sourcePosition,
                 destination,
                 destinationPosition,
                 length);
 

Method 3: Java Streams

 
import java.util.Arrays;
import java.util.stream.IntStream;

int[] merged = IntStream.concat(
        Arrays.stream(array1),
        Arrays.stream(array2)
).toArray();
 

IntStream.concat() joins two streams into one and converts the result back into an array.

This solution is concise and well suited for stream-based applications.


Method 4: Merging Two Sorted Arrays

If both input arrays are already sorted, you can merge them while preserving sorted order.

 
public static int[] mergeSorted(int[] a, int[] b) {

    int[] result = new int[a.length + b.length];

    int i = 0;
    int j = 0;
    int k = 0;

    while (i < a.length && j < b.length) {

        if (a[i] <= b[j]) {
            result[k++] = a[i++];
        } else {
            result[k++] = b[j++];
        }
    }

    while (i < a.length) {
        result[k++] = a[i++];
    }

    while (j < b.length) {
        result[k++] = b[j++];
    }

    return result;
}
 

This is the same merge step used in the Merge Sort algorithm and runs in O(n + m) time.


Step-by-Step Explanation

Manual Loop Merge

Create a new array whose size is the sum of both input arrays.

Copy every element from the first array.

Then copy every element from the second array.

Using System.arraycopy()

The destination array is created once.

The first call copies every element from the first array.

The second call copies the second array immediately after the first one.

Merging Sorted Arrays

Three indices are maintained:

  • i traverses the first array.
  • j traverses the second array.
  • k tracks the insertion position in the merged array.

During each step, the smaller element is copied into the result array.

Once one array is exhausted, all remaining elements from the other array are copied.


Internal Working (Memory View)

Merging:

 
{1, 3, 5}

{2, 4, 6}
 

Processing:

 
Compare 1 and 2

Result = [1]

Compare 3 and 2

Result = [1, 2]

Compare 3 and 4

Result = [1, 2, 3]

Compare 5 and 4

Result = [1, 2, 3, 4]

Compare 5 and 6

Result = [1, 2, 3, 4, 5]

First array finished

Copy remaining element

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

Real-Life Analogy

Imagine two people each holding a stack of cards already sorted from smallest to largest.

Instead of combining the stacks and sorting everything again, they repeatedly compare the top card from each stack and place the smaller one into a new pile.

This produces one fully sorted stack without any unnecessary sorting.


Best Practices

  • Use System.arraycopy() for efficiently concatenating arrays.
  • Use the manual loop when learning array manipulation fundamentals.
  • Use the two-pointer merge algorithm when both arrays are already sorted.
  • Use IntStream.concat() for concise stream-based code when readability is more important than raw performance.

Common Mistakes

  1. Concatenating two sorted arrays and sorting them again instead of using the linear-time merge algorithm.
  2. Allocating the merged array with the wrong size.
  3. Mixing up the parameters of System.arraycopy().
  4. Forgetting to copy the remaining elements after one sorted array has been completely processed.

Expert Tips

  • Memorize the parameter order of System.arraycopy() because it is widely used throughout the Java Standard Library.
  • The sorted merge algorithm is the core operation of Merge Sort, so mastering it helps when learning sorting algorithms.
  • When merging arrays of custom objects, replace the comparison with a Comparator instead of using natural ordering.

Comparison Table

Method Time Complexity Best Use Case
Manual Loop O(n + m) Learning array fundamentals
System.arraycopy() O(n + m) General-purpose array merging
Java Streams (IntStream.concat) O(n + m) Functional-style programming
Two-Pointer Sorted Merge O(n + m) Merging two sorted arrays while preserving order

Frequently Asked Questions

What is the fastest way to merge two arrays in Java?

System.arraycopy() is generally the fastest method because it performs a native memory copy optimized by the JVM.

How do I merge two sorted arrays while keeping the result sorted?

Use the two-pointer merge algorithm, which processes both arrays simultaneously in O(n + m) time.

Is concatenating and sorting efficient for already sorted arrays?

No. It takes O((n + m) log(n + m)), whereas the two-pointer merge algorithm requires only O(n + m).

What does System.arraycopy() do internally?

It is a native JVM method that performs a highly optimized memory copy from one array to another.

Can I merge more than two arrays?

Yes. You can repeatedly merge arrays one at a time or loop through multiple arrays while copying their elements into a larger destination array.

How can I merge arrays without duplicates?

Merge the arrays first, then remove duplicate values using techniques such as LinkedHashSet or Java Streams with distinct().

Does IntStream.concat() preserve the original order?

Yes. The resulting stream contains all elements of the first array followed by all elements of the second array.

It is the exact merge step used by Merge Sort. The sorting algorithm repeatedly divides arrays into smaller parts and then combines them using this same merging technique.