SwadhyAI Notes

All Java notes

How to Merge Two Arrays in Java

The Challenge

Combine two arrays into a single array!

Solutions

Method 1: Using System.arraycopy()

java
int[] arr1 = {1, 2, 3};
int[] arr2 = {4, 5, 6};
int[] merged = new int[arr1.length + arr2.length];

System.arraycopy(arr1, 0, merged, 0, arr1.length);
System.arraycopy(arr2, 0, merged, arr1.length, arr2.length);

System.out.println(Arrays.toString(merged));
// Output: [1, 2, 3, 4, 5, 6]

Method 2: Using Loop

java
int[] arr1 = {1, 2, 3};
int[] arr2 = {4, 5, 6};
int[] merged = new int[arr1.length + arr2.length];

int index = 0;
for (int num : arr1) {
    merged[index++] = num;
}
for (int num : arr2) {
    merged[index++] = num;
}

System.out.println(Arrays.toString(merged));
// Output: [1, 2, 3, 4, 5, 6]

Method 3: Using Java 8 Streams

java
import java.util.stream.IntStream;

int[] arr1 = {1, 2, 3};
int[] arr2 = {4, 5, 6};
int[] merged = IntStream.concat(
    Arrays.stream(arr1),
    Arrays.stream(arr2)
).toArray();

System.out.println(Arrays.toString(merged));
// Output: [1, 2, 3, 4, 5, 6]

Did You Know?

System.arraycopy() is a native method optimized for performance - it's the fastest way to copy arrays!

Real-World Use Cases

  • Data processing: Combine datasets
  • File handling: Merge file contents
  • Collections: Combine multiple lists
›Short versionOpen if you only have a minute.
  • Concatenation allocates length a + length b and copies each array into its half.
  • A result allocated with the wrong length throws, or drops the tail.
  • Copying does not sort. {1, 4} then {2, 3} becomes {1, 4, 2, 3}.
  • A sorted merge is a different algorithm: two indexes, always take the smaller head.

Merge two arrays

Combine two arrays into one array.

Working approach

  • Allocate a result of combined length.
  • Copy with System.arraycopy or a loop.
  • Use a two-pointer merge only when both inputs are sorted and the output must be sorted too.

Walk the sample

  1. Left {1, 2}, right {3, 4}
  2. Result length 4
  3. Copy left into indexes 0 and 1
  4. Copy right into indexes 2 and 3

The trap

The copy recipe is not a sorted merge. Callers who pass sorted arrays and expect a sorted result get the two halves glued together.

java
static int[] concat(int[] left, int[] right) {
    int[] merged = new int[left.length + right.length];
    System.arraycopy(left, 0, merged, 0, left.length);
    System.arraycopy(right, 0, merged, left.length, right.length);
    return merged;
}

Does copying {1, 4} and then {2, 3} leave the result sorted?

No. The result is {1, 4, 2, 3}.

A sorted merge walks both arrays and appends the smaller current head. Use that when sorted order was the point. The concatenation above is the recipe that matches an unordered merge.

Time O(n + m), space O(n + m).

Easy to get wrong

  • Allocating a result as long as only one input.
  • Assuming concatenation preserves sorted order.