How can I concatenate two arrays in Java?
Concatenating two arrays in Java isn’t as straightforward as in some other languages because Java arrays have fixed sizes. You can’t just “append” to an existing array; instead, you have to create a new array and copy elements into it. Below are three popular methods to achieve this, along with some performance considerations and tips to help you stand out in interviews or real-world projects.
1. Using a Loop and a New Array
Step-by-Step
- Create a new array of size
arr1.length + arr2.length
. - Copy elements from the first array.
- Copy elements from the second array.
public static int[] concatenateArrays(int[] arr1, int[] arr2) { int[] result = new int[arr1.length + arr2.length]; int index = 0; // Copy first array for (int value : arr1) { result[index++] = value; } // Copy second array for (int value : arr2) { result[index++] = value; } return result; }
- Pros: Straightforward and easy to understand.
- Cons: Verbose if you need to do this frequently.
2. Using System.arraycopy()
System.arraycopy()
is a highly optimized method for copying data at the native system level.
public static int[] concatenateArraysUsingSystem(int[] arr1, int[] arr2) { int[] result = new int[arr1.length + arr2.length]; System.arraycopy(arr1, 0, result, 0, arr1.length); System.arraycopy(arr2, 0, result, arr1.length, arr2.length); return result; }
- Pros: Less boilerplate code than using loops manually. Often faster in practice.
- Cons: The method signature can be a bit confusing at first (
srcPos
,destPos
, etc.).
3. Using Java 8+ Streams
If you’re working with Java 8 and above, you can use Streams to handle the concatenation in a more functional style.
import java.util.Arrays; import java.util.stream.IntStream; public static int[] concatenateWithStreams(int[] arr1, int[] arr2) { return IntStream .concat(Arrays.stream(arr1), Arrays.stream(arr2)) .toArray(); }
- Pros: Elegant, concise, and leverages the power of the Streams API.
- Cons: Less efficient than
System.arraycopy()
due to stream overhead. Might be overkill for simple cases.
Performance Considerations
- Time Complexity: All methods run in O(n + m) where
n
is the size of the first array andm
is the size of the second array. You have to read every element at least once. - Space Complexity: The result array requires O(n + m) additional space since a brand-new array is created.
- Memory Allocation: Inserting into arrays dynamically isn’t possible. If you need frequent insertions, consider using a
List
(e.g.,ArrayList
) for better efficiency in dynamic scenarios.
Interview Tips
- Discuss Trade-offs: Show that you know
System.arraycopy()
is often faster, while Streams can be more readable but might incur performance overhead. - Mention Alternatives: In real-world code, you might use
List
operations and then convert back to an array withlist.toArray()
if you need frequent modifications. - Edge Cases: Consider arrays of size
0
(empty arrays), arrays with negative values, or arrays containing objects.
Strengthen Your Coding Skills
If you want to master array operations and data structures for coding interviews, here are a few recommended resources from DesignGurus.io:
- Grokking Data Structures & Algorithms for Coding Interviews: Deep-dive into arrays, linked lists, trees, graphs, and more—perfect for nailing the basics that frequently appear in interviews.
- Grokking the Coding Interview: Patterns for Coding Questions: Recognize and apply the most common coding patterns to quickly solve typical interview challenges.
- Grokking JavaScript Fundamentals: Learn JavaScript fundamentals.
If you’re looking for personalized feedback on your coding or system design approach, consider a Coding Mock Interview session with ex-FAANG engineers. You can also explore the DesignGurus YouTube Channel for free tutorials, tips, and deep dives into interview strategies.
Conclusion
Concatenating arrays in Java requires creating a new array and populating it. Whether you choose a manual loop, System.arraycopy()
, or Java 8 Streams, the key is understanding each method’s trade-offs in readability and performance. Mastering these fundamental array operations will serve you well in both coding interviews and production-level development. Happy coding!