eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

1. Overview

In this tutorial, we’re going to discuss how to concatenate two arrays in Java.

First, we’ll implement our own methods with the standard Java API.

Then, we’ll have a look at how to solve the problem using commonly used libraries.

2. Introduction to the Problem

Quick examples may explain the problem clearly.

Let’s say, we have two arrays:

String[] strArray1 = {"element 1", "element 2", "element 3"};
String[] strArray2 = {"element 4", "element 5"};

Now, we want to join them and get a new array:

String[] expectedStringArray = {"element 1", "element 2", "element 3", "element 4", "element 5"}

Also, we don’t want our method only to work with String arrays, so we’ll look for a generic solution.

Moreover, we shouldn’t forget the primitive array cases. It would be good if our solution works for primitive arrays, too:

int[] intArray1 = { 0, 1, 2, 3 };
int[] intArray2 = { 4, 5, 6, 7 };
int[] expectedIntArray = { 0, 1, 2, 3, 4, 5, 6, 7 };

In this tutorial, we’ll address different approaches to solve the problem.

3. Using Java Collections

When we look at this problem, a quick solution may come up.

Well, Java doesn’t provide a helper method to concatenate arrays. However, since Java 5, the Collections utility class has introduced an addAll(Collection<? super T> c, T… elements) method.

We can create a List object, then call this method twice to add the two arrays to the list. Finally, we convert the resulting List back to an array:

static <T> T[] concatWithCollection(T[] array1, T[] array2) {
    List<T> resultList = new ArrayList<>(array1.length + array2.length);
    Collections.addAll(resultList, array1);
    Collections.addAll(resultList, array2);

    @SuppressWarnings("unchecked")
    //the type cast is safe as the array1 has the type T[]
    T[] resultArray = (T[]) Array.newInstance(array1.getClass().getComponentType(), 0);
    return resultList.toArray(resultArray);
}

In the method above, we use Java reflection API to create a generic array instance: resultArray.

Let’s write a test to verify if our method works:

@Test
public void givenTwoStringArrays_whenConcatWithList_thenGetExpectedResult() {
    String[] result = ArrayConcatUtil.concatWithCollection(strArray1, strArray2);
    assertThat(result).isEqualTo(expectedStringArray);
}

If we execute the test, it’ll pass.

This approach is pretty straightforward. However, since the method accepts T[] arrays, it doesn’t support concatenating primitive arrays.

Apart from that, it’s inefficient as it creates an ArrayList object, and later we call the toArray() method to convert it back to an array. In this procedure, the Java List object adds unnecessary overhead.

Next, let’s see if we can find a more efficient way to solve the problem.

4. Using the Array Copy Technique

Java doesn’t offer an array concatenation method, but it provides two array copy methods: System.arraycopy() and Arrays.copyOf().

We can solve the problem using Java’s array copy methods.

The idea is, we create a new array, say result, which has result.length = array1.length + array2.length, and copy each array’s elements to the result array.

4.1. Non-Primitive Arrays

First, let’s have a look at the method implementation:

static <T> T[] concatWithArrayCopy(T[] array1, T[] array2) {
    T[] result = Arrays.copyOf(array1, array1.length + array2.length);
    System.arraycopy(array2, 0, result, array1.length, array2.length);
    return result;
}

The method looks compact. Further, the whole method has created only one new array object: result.

Now, let’s write a test method to check if it works as we expect:

@Test
public void givenTwoStringArrays_whenConcatWithCopy_thenGetExpectedResult() {
    String[] result = ArrayConcatUtil.concatWithArrayCopy(strArray1, strArray2);
    assertThat(result).isEqualTo(expectedStringArray);
}

The test will pass if we give it a run.

There is no unnecessary object creation. Thus, this method is more performant than the approach using Java Collections.

On the other hand, this generic method only accepts parameters with the T[] type. Therefore, we cannot pass primitive arrays to the method.

However, we can modify the method to make it support primitive arrays.

Next, let’s take a closer look at how to add primitive array support.

4.2. Add Primitive Array Support

To make the method support primitive arrays, we need to change the parameters’ type from T[] to T and do some type-safe checks.

First, let’s take a look at the modified method:

static <T> T concatWithCopy2(T array1, T array2) {
    if (!array1.getClass().isArray() || !array2.getClass().isArray()) {
        throw new IllegalArgumentException("Only arrays are accepted.");
    }

    Class<?> compType1 = array1.getClass().getComponentType();
    Class<?> compType2 = array2.getClass().getComponentType();

    if (!compType1.equals(compType2)) {
        throw new IllegalArgumentException("Two arrays have different types.");
    }

    int len1 = Array.getLength(array1);
    int len2 = Array.getLength(array2);

    @SuppressWarnings("unchecked")
    //the cast is safe due to the previous checks
    T result = (T) Array.newInstance(compType1, len1 + len2);

    System.arraycopy(array1, 0, result, 0, len1);
    System.arraycopy(array2, 0, result, len1, len2);

    return result;
}

Obviously, the concatWithCopy2() method is longer than the original version. But it’s not hard to understand. Now, let’s quickly walk through it to understand how it works.

Since the method now allows parameters with the type T, we need to make sure both parameters are arrays:

if (!array1.getClass().isArray() || !array2.getClass().isArray()) {
    throw new IllegalArgumentException("Only arrays are accepted.");
}

It’s still not safe enough if two parameters are arrays. For example, we don’t want to concatenate an Integer[] array and a String[] array. So, we need to make sure the ComponentType of the two arrays are identical:

if (!compType1.equals(compType2)) {
    throw new IllegalArgumentException("Two arrays have different types.");
}

After the type-safe checks, we can create a generic array instance using the ConponentType object and copy parameter arrays to the result array. It’s quite similar to the previous concatWithCopy() method.

4.3. Testing the concatWithCopy2() Method

Next, let’s test if our new method works as we expected. First, we pass two non-array objects and see if the method raises the expected exception:

@Test
public void givenTwoStrings_whenConcatWithCopy2_thenGetException() {
    String exMsg = "Only arrays are accepted.";
    try {
        ArrayConcatUtil.concatWithCopy2("String Nr. 1", "String Nr. 2");
        fail(String.format("IllegalArgumentException with message:'%s' should be thrown. But it didn't", exMsg));
    } catch (IllegalArgumentException e) {
        assertThat(e).hasMessage(exMsg);
    }
}

In the test above, we pass two String objects to the method. If we execute the test, it passes. This means we’ve got the expected exception.

Finally, let’s build a test to check if the new method can concatenate primitive arrays:

@Test
public void givenTwoArrays_whenConcatWithCopy2_thenGetExpectedResult() {
    String[] result = ArrayConcatUtil.concatWithCopy2(strArray1, strArray2);
    assertThat(result).isEqualTo(expectedStringArray);

    int[] intResult = ArrayConcatUtil.concatWithCopy2(intArray1, intArray2);
    assertThat(intResult).isEqualTo(expectedIntArray);
}

This time, we called the concatWithCopy2() method twice. First, we pass two String[] arrays. Then, we pass two int[] primitive arrays.

The test will pass if we run it. Now, we can say, the concatWithCopy2() method works as we expected.

5. Using Java Stream API

If the Java version we’re working with is 8 or newer, the Stream API is available. We can also resolve the problem using the Stream API.

First, we can get a Stream from an array by the Arrays.stream() method. Also, the Stream class provides a static concat() method to concatenate two Stream objects.

Now, let’s see how to concatenate two arrays with Stream.

5.1. Concatenating Non-Primitive Arrays

Building a generic solution using Java Streams is pretty simple:

static <T> T[] concatWithStream(T[] array1, T[] array2) {
    return Stream.concat(Arrays.stream(array1), Arrays.stream(array2))
      .toArray(size -> (T[]) Array.newInstance(array1.getClass().getComponentType(), size));
}

First, we convert two input arrays to Stream objects. Second, we concatenate the two Stream objects using the Stream.concat() method.

Finally, we return an array containing all elements in the concatenated Stream.

Next, let’s build a simple test method to check if the solution works:

@Test
public void givenTwoStringArrays_whenConcatWithStream_thenGetExpectedResult() {
    String[] result = ArrayConcatUtil.concatWithStream(strArray1, strArray2);
    assertThat(result).isEqualTo(expectedStringArray);
}

The test will pass if we pass two String[] arrays.

Probably, we’ve noticed that our generic method accepts parameters in the T[] type. Therefore, it won’t work for primitive arrays.

Next, let’s see how to concatenate two primitive arrays using Java Streams.

5.2. Concatenating Primitive Arrays

The Stream API ships different Stream classes that can convert the Stream object to the corresponding primitive array, such as IntStream, LongStream, and DoubleStream.

However, only int, long, and double have their Stream types. That is to say, if the primitive arrays we want to concatenate have type int[], long[], or double[], we can pick the right Stream class and invoke the concat() method.

Let’s see an example to concatenate two int[] arrays using IntStream:

static int[] concatIntArraysWithIntStream(int[] array1, int[] array2) {
    return IntStream.concat(Arrays.stream(array1), Arrays.stream(array2)).toArray();
}

As the method above shows, the Arrays.stream(int[]) method will return an IntStream object.

Also, the IntStream.toArray() method returns int[]. Therefore, we don’t need to take care of the type conversions.

As usual, let’s create a test to see if it works with our int[] input data:

@Test
public void givenTwoIntArrays_whenConcatWithIntStream_thenGetExpectedResult() {
    int[] intResult = ArrayConcatUtil.concatIntArraysWithIntStream(intArray1, intArray2);
    assertThat(intResult).isEqualTo(expectedIntArray);
}

If we run the test, it’ll pass.

6. Using the Apache Commons Lang Library

The Apache Commons Lang library is widely used in Java applications in the real world.

It ships with an ArrayUtils class, which contains many handy array helper methods.

The ArrayUtils class provides a series of addAll() methods, which support concatenating both non-primitive and primitive arrays.

Let’s verify it by a test method:

@Test
public void givenTwoArrays_whenConcatWithCommonsLang_thenGetExpectedResult() {
    String[] result = ArrayUtils.addAll(strArray1, strArray2);
    assertThat(result).isEqualTo(expectedStringArray);

    int[] intResult = ArrayUtils.addAll(intArray1, intArray2);
    assertThat(intResult).isEqualTo(expectedIntArray);
}

Internally, the ArrayUtils.addAll() methods use the performant System.arraycopy() method to do the array concatenation.

7. Using the Guava Library

Similar to the Apache Commons library, Guava is another library loved by many developers.

Guava provides convenient helper classes to do array concatenation as well.

If we want to concatenate non-primitive arrays, the ObjectArrays.concat() method is a good choice:

@Test
public void givenTwoStringArrays_whenConcatWithGuava_thenGetExpectedResult() {
    String[] result = ObjectArrays.concat(strArray1, strArray2, String.class);
    assertThat(result).isEqualTo(expectedStringArray);
}

Guava has offered primitive utilities for each primitive. All primitive utilities provide concat() method to concatenate the arrays with the corresponding types, for example:

  • int[] – Guava: Ints.concat(int[] … arrays)
  • long[] – Guava: Longs.concat(long[] … arrays)
  • byte[] – Guava: Bytes.concat(byte[] … arrays)
  • double[] – Guava: Doubles.concat(double[] … arrays)

We can just pick the right primitive utility class to concatenate primitive arrays.

Next, let’s concatenate our two int[] arrays using the Ints.concat() method:

@Test
public void givenTwoIntArrays_whenConcatWithGuava_thenGetExpectedResult() {
    int[] intResult = Ints.concat(intArray1, intArray2);
    assertThat(intResult).isEqualTo(expectedIntArray);
}

Similarly, Guava internally uses System.arraycopy() in the above-mentioned methods to do the array concatenation to gain good performance.

8. Conclusion

In this article, we’ve addressed different approaches to concatenate two arrays in Java through examples.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)