Concatenate Arrays in Java
Problem
Concatenating two arrays means placing every element of the first array followed by every element of the second, into one combined array.
Given two arrays of integers, combine them into a single array holding every element from both, in order.
Java Program
import java.util.Arrays;
public class ConcatenateArrays {
public static void main(String[] args) {
int[] arr1 = {2, 4, 6};
int[] arr2 = {7, 9};
int[] result = new int[arr1.length + arr2.length];
for (int i = 0; i < arr1.length; i++) {
result[i] = arr1[i];
}
for (int i = 0; i < arr2.length; i++) {
result[arr1.length + i] = arr2[i]; // offset past arr1's elements
}
System.out.println("Concatenated array: " + Arrays.toString(result));
}
}Output
Core Logic
Allocating a new array sized to hold both inputs, then copying each one into its own section, joins them end to end.
- 1
int[] result = new int[arr1.length + arr2.length]allocates an array large enough for every element from both inputs. - 2The first loop copies each element of
arr1intoresult, starting at index 0. - 3The second loop copies each element of
arr2intoresult, starting right after wherearr1's elements ended — at indexarr1.length + i. - 4The result holds every element from
arr1first, followed by every element fromarr2.
[2, 4, 6] and [7, 9], the result array is sized 5, with 2, 4, 6 copied to indices 0-2 and 7, 9 copied to indices 3-4.Key Point: The offset arr1.length + i is what prevents the second array's elements from overwriting the first — without it, both copies would start at index 0.
Why: Every element from both arrays is visited once, and the result array holds all of them combined.
Key Concepts
Approach 2: Java 8
import java.util.Arrays;
import java.util.stream.IntStream;
public class ConcatenateArraysStream {
public static void main(String[] args) {
int[] arr1 = {2, 4, 6};
int[] arr2 = {7, 9};
// Joins both streams end to end, then collects the result into an array
int[] result = IntStream.concat(Arrays.stream(arr1), Arrays.stream(arr2)).toArray();
System.out.println("Concatenated array: " + Arrays.toString(result));
}
}
Output
Core Logic
IntStream.concat() joins two streams end to end directly, without manually tracking index offsets.
- 1
Arrays.stream(arr1)andArrays.stream(arr2)each convert theirint[]into anIntStream. - 2
IntStream.concat(...)joins the two streams together, with every element from the first stream before every element from the second. - 3
.toArray()collects the combined stream into a brand-newint[].
IntStream.concat(Arrays.stream({2, 4, 6}), Arrays.stream({7, 9})) produces a stream of 2, 4, 6, 7, 9, collected into the result array.Key Point: concat() handles the index bookkeeping internally — there's no equivalent of the manual version's arr1.length + i offset to get wrong.
Why: The concatenated stream still visits every element from both arrays once, and toArray() builds a result array holding all of them.