Question

How to Concatenate Two Arrays in Java

javaarraysconcatenationaddition

Question

I need to combine two String arrays into one array in Java.

void f(String[] first, String[] second) {
    String[] both = ???;
}

What is the simplest and most practical way to concatenate these two arrays?

Short Answer

By the end of this page, you will understand how array concatenation works in Java, why arrays cannot grow automatically, and how to combine two String[] values into a new array using standard Java techniques such as System.arraycopy, loops, and streams.

Concept

In Java, an array has a fixed size. Once you create it, you cannot expand it. That is why concatenating two arrays does not mean modifying one of them to make room for the other. Instead, you create a new array large enough to hold both arrays, then copy the elements from the first array and the second array into it.

For example, if first has length 2 and second has length 3, the combined array must have length 5.

This matters because arrays are common in Java, especially when working with low-level APIs, method parameters, configuration values, and performance-sensitive code. Understanding that arrays are fixed-size helps you choose the right tool:

  • Use an array when the size is known or fixed.
  • Use a List when you need something that can grow or shrink.

For concatenating arrays, the core idea is always the same:

  1. Create a new array with enough space.
  2. Copy the first array into the beginning.
  3. Copy the second array after it.

Mental Model

Think of an array like a row of numbered boxes.

If you have one row with 3 boxes and another row with 2 boxes, you cannot "stretch" the first row to fit more boxes. Instead, you build a new row with 5 boxes and move everything into it.

  • Boxes 0 to first.length - 1 hold the first array.
  • Boxes starting at first.length hold the second array.

So concatenation in Java arrays is really create a new container and copy values into it.

Take Quiz

Syntax and Examples

Basic approach with System.arraycopy

void f(String[] first, String[] second) {
    String[] both = new String[first.length + second.length];
    System.arraycopy(first, 0, both, 0, first.length);
    System.arraycopy(second, 0, both, first.length, second.length);
}

How it works

  • new String[first.length + second.length] creates a new array large enough for both inputs.
  • The first arraycopy copies all elements from first into both starting at index 0.
  • The second arraycopy copies all elements from second into both starting at index first.length.

Complete example

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String[] first = {"A", "B"};
        String[] second = {"C", "D"};

        String[] both = new String[first.length + second.length];
        System.arraycopy(first, 0, both, 0, first.length);
        System.arraycopy(second, 0, both, first.length, second.length);

        System.out.println(Arrays.toString(both));
    }
}

Output:

[A, B, C, D]

Alternative using Arrays.copyOf

import java.util.Arrays;

String[] both = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, both, first.length, second.length);

This is often seen as clean and readable because it copies the first array for you, then appends the second.

Alternative using streams

import java.util.stream.Stream;

String[] both = Stream.concat(Arrays.stream(first), Arrays.stream(second))
                      .toArray(String[]::new);

This works well, but for simple array concatenation, it is usually less direct than System.arraycopy.

Step by Step Execution

Consider this example:

String[] first = {"red", "blue"};
String[] second = {"green", "yellow"};

String[] both = new String[first.length + second.length];
System.arraycopy(first, 0, both, 0, first.length);
System.arraycopy(second, 0, both, first.length, second.length);

Step 1: Create the input arrays

  • first contains 2 elements: "red", "blue"
  • second contains 2 elements: "green", "yellow"

Step 2: Create the result array

String[] both = new String[first.length + second.length];
  • first.length is 2
  • second.length is 2
  • total size is 4

Now both looks like this:

[null, null, null, null]

Step 3: Copy the first array

System.arraycopy(first, 0, both, 0, first.length);

Meaning:

  • copy from first
  • start at index 0 in first
  • paste into both
  • start at index 0 in both
  • copy 2 items

Now both becomes:

[red, blue, null, null]

Step 4: Copy the second array

System.arraycopy(second, 0, both, first.length, second.length);

Here first.length is 2, so copying starts at index 2 in both.

Now both becomes:

[red, blue, green, yellow]

That is the final concatenated array.

Real World Use Cases

Array concatenation appears in many practical Java programs:

  • Command-line tools: combine default arguments with user-provided arguments.
  • Configuration loading: merge built-in values with environment-specific values.
  • Data processing: join batches of values before passing them to another method.
  • Testing: combine base test data with case-specific inputs.
  • API adapters: merge headers, tokens, or parameter arrays before sending data onward.

Example: combining default and extra tags:

String[] defaultTags = {"java", "backend"};
String[] extraTags = {"arrays", "strings"};

String[] allTags = new String[defaultTags.length + extraTags.length];
System.arraycopy(defaultTags, 0, allTags, 0, defaultTags.length);
System.arraycopy(extraTags, 0, allTags, defaultTags.length, extraTags.length);

This pattern is simple, fast, and common when an API specifically requires arrays.

Take Quiz

Real Codebase Usage

In real projects, developers often choose one of these patterns depending on context.

1. Utility method for reuse

If concatenation happens in several places, it is usually wrapped in a helper method.

public static String[] concat(String[] first, String[] second) {
    String[] result = new String[first.length + second.length];
    System.arraycopy(first, 0, result, 0, first.length);
    System.arraycopy(second, 0, result, first.length, second.length);
    return result;
}

This keeps calling code clean.

2. Guard clauses for null

In production code, arrays may sometimes be null.

public static String[] concat(String[] first, String[] second) {
    if (first == null) return second == null ? new String[0] : second.clone();
    if (second == null) return first.clone();

    String[] result = new String[first.length + second.length];
    System.arraycopy(first, 0, result, 0, first.length);
    System.arraycopy(second, 0, result, first.length, second.length);
    return result;
}

Guard clauses make the method safer.

3. Prefer List when size changes often

If code repeatedly adds and removes elements, developers usually switch to ArrayList instead of constantly creating new arrays.

4. Preserve immutability

Returning a new array rather than editing inputs avoids surprising side effects. This is a good practice in shared codebases.

Common Mistakes

1. Trying to use + like strings

Broken code:

String[] both = first + second;

Why it fails:

  • Java allows + for strings and numbers.
  • It does not concatenate arrays this way.

2. Forgetting to create enough space

Broken code:

String[] both = new String[first.length];
System.arraycopy(second, 0, both, first.length, second.length);

Why it fails:

  • both is too small.
  • Copying the second array will cause an ArrayIndexOutOfBoundsException.

Fix:

String[] both = new String[first.length + second.length];

3. Using the wrong destination start index

Broken code:

System.arraycopy(second, 0, both, 0, second.length);

Why it is wrong:

  • This starts writing second at the beginning of both.
  • It overwrites the values copied from first.

Correct version:

System.arraycopy(second, 0, both, first.length, second.length);

4. Forgetting that arrays are fixed-size

Beginners sometimes expect arrays to grow automatically. They do not. You always need a new array for concatenation.

5. Not handling null when needed

Broken code:

String[] both = new String[first.length + second.length];

If first or second is null, this throws a NullPointerException.

If null is possible, add checks before using .length.

Comparisons

ApproachExampleBest forNotes
System.arraycopyCopy first and second into a new arrayMost common and efficient array concatenationClear and fast
Arrays.copyOf + System.arraycopyCopy first, then append secondReadable codeConvenient when starting from the first array
Manual loopUse for loops to copy valuesLearning or custom logicMore verbose
Stream APIStream.concat(...)Functional-style codeLess direct for simple arrays
ArrayListAdd elements dynamicallyWhen size changes oftenBetter than arrays for frequent resizing

Arrays vs Lists

FeatureArrayArrayList
SizeFixedDynamic
ConcatenationRequires new arrayEasy with addAll()
PerformanceVery efficient for fixed-size dataFlexible, slightly higher overhead
SyntaxSimple low-level structureMore convenient for app logic

If you only need to combine two existing arrays, use array copying. If your data keeps growing, use a List.

Take Quiz

Cheat Sheet

Quick reference

Concatenate two String[] arrays

String[] both = new String[first.length + second.length];
System.arraycopy(first, 0, both, 0, first.length);
System.arraycopy(second, 0, both, first.length, second.length);

Alternative

String[] both = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, both, first.length, second.length);

System.arraycopy parameters

System.arraycopy(source, sourceStart, destination, destinationStart, length);

Important rules

  • Arrays in Java have fixed length.
  • Concatenation creates a new array.
  • The destination array must be large enough for all elements.
  • The second copy should start at index first.length.
  • If null is possible, check for it before using .length.

Common pattern

public static String[] concat(String[] first, String[] second) {
    String[] result = new String[first.length + second.length];
    System.arraycopy(first, 0, result, 0, first.length);
    System.arraycopy(second, 0, result, first.length, second.length);
    return result;
}

FAQ

How do you concatenate two arrays in Java?

Create a new array with combined length, then copy the first and second arrays into it using System.arraycopy or a loop.

Can I use + to join arrays in Java?

No. The + operator does not concatenate arrays in Java.

What is the easiest way to combine two String[] arrays?

A common choice is System.arraycopy, because it is simple, built into Java, and efficient.

Is there a built-in one-line method for array concatenation in Java?

Not for plain arrays in core Java. You usually combine Arrays.copyOf and System.arraycopy, or use streams.

Should I use arrays or ArrayList?

Use arrays when the size is fixed. Use ArrayList when you need to add or remove items often.

What happens if one array is empty?

The code still works. The result will simply contain the elements from the non-empty array.

What happens if one array is null?

You will get a NullPointerException unless you handle null first.

Take Quiz

Mini Project

Description

Build a small Java utility method that merges two arrays of tags into one result array. This demonstrates the standard array concatenation pattern used in real applications when data comes from two separate sources.

Goal

Create a reusable method that concatenates two String[] arrays and prints the combined result.

Requirements

  1. Create a method named concat that accepts two String[] parameters.
  2. Return a new array containing all elements of the first array followed by all elements of the second array.
  3. Use standard Java array copying instead of converting to a list.
  4. In main, call the method with sample data and print the result.
  5. Ensure the code runs as a complete Java program.
Take Quiz

Keep learning

Related questions

View more