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.

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

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

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

In this tutorial, we’ll briefly look at the similarities and dissimilarities in memory allocation between Java arrays and the standard ArrayList. Furthermore, we’ll see how to append and insert elements in an array and ArrayList.

2. Java Arrays and ArrayList

A Java array is a basic data structure provided by the language. In contrast, ArrayList is an implementation of the List interface backed by an array and is provided in the Java Collections Framework.

2.1. Accessing and Modifying Elements

We can access and modify array elements using the square brackets notation:

System.out.println(anArray[1]);
anArray[1] = 4;

On the other hand, ArrayList has a set of methods to access and modify elements:

int n = anArrayList.get(1);
anArrayList.set(1, 4);

2.2. Fixed vs Dynamic Size

An array and the ArrayList both allocate heap memory in a similar manner, but what differs is that an array is fixed-sized, while the size of an ArrayList increases dynamically.

Since a Java array is fixed-sized, we need to provide the size while instantiating it. It is not possible to increase the size of the array once it has been instantiated. Instead, we need to create a new array with the adjusted size and copy all the elements from the previous array.

ArrayList is a resizable array implementation of the List interface — that is, ArrayList grows dynamically as elements are added to it. When the number of current elements (including the new element to be added to the ArrayList) is greater than the maximum size of its underlying array, then the ArrayList increases the size of the underlying array.

The growth strategy for the underlying array depends on the implementation of the ArrayList. However, since the size of the underlying array cannot be increased dynamically, a new array is created and the old array elements are copied into the new array.

The add operation has a constant amortized time cost. In other words, adding n elements to an ArrayList requires O(n) time.

2.3. Element Types

An array can contain primitive as well as non-primitive data types, depending on the definition of the array. However, an ArrayList can only contain non-primitive data types.

When we insert elements with primitive data types into an ArrayList, the Java compiler automatically converts the primitive data type into its corresponding object wrapper class.

Let’s now look at how to append and insert elements in Java arrays and the ArrayList.

3. Appending an Element

As we’ve already seen, arrays are of fixed size.

So, to append an element, first, we need to declare a new array that is larger than the old array and copy the elements from the old array to the newly created array. After that, we can append the new element to this newly created array.

Let’s look at its implementation in Java without using any utility classes:

public Integer[] addElementUsingPureJava(Integer[] srcArray, int elementToAdd) {
    Integer[] destArray = new Integer[srcArray.length+1];

    for(int i = 0; i < srcArray.length; i++) {
        destArray[i] = srcArray[i];
    }

    destArray[destArray.length - 1] = elementToAdd;
    return destArray;
}

Alternately, the Arrays class provides a utility method copyOf(), which assists in creating a new array of larger size and copying all the elements from the old array:

int[] destArray = Arrays.copyOf(srcArray, srcArray.length + 1);

Once we have created a new array, we can easily append the new element to the array:

destArray[destArray.length - 1] = elementToAdd;

On the other hand, appending an element in ArrayList is quite easy:

anArrayList.add(newElement);

4. Inserting an Element at Index

Inserting an element at a given index without losing the previously added elements is not a simple task in arrays.

First of all, if the array already contains the number of elements equal to its size, then we first need to create a new array with a larger size and copy the elements over to the new array.

Furthermore, we need to shift all elements that come after the specified index by one position to the right:

public static int[] insertAnElementAtAGivenIndex(final int[] srcArray, int index, int newElement) {
    int[] destArray = new int[srcArray.length+1];
    int j = 0;
    for(int i = 0; i < destArray.length; i++) {

        if(i == index) {
            destArray[i] = newElement;
        } else {
            destArray[i] = srcArray[j];
            j++;
        }
    }
    return destArray;
}

Next, let’s create a test to verify if this method works as expected:

int[] expectedArray = { 1, 2, 42, 3, 4 };
int[] anArray = { 1, 2, 3, 4 };
int[] outputArray = ArrayOperations.insertAnElementAtAGivenIndex(anArray, 2, 42);
 
assertThat(outputArray).containsExactly(expectedArray);

The ArrayUtils class from the popular Apache Commons Lang 3 library gives us a simpler solution to insert items into an array:

int[] destArray = ArrayUtils.insert(2, srcArray, 77);

We have to specify the index at which we want to insert the value, the source array, and the value to insert.

The insert() method returns a new array containing a larger number of elements, with the new element at the specified index and all remaining elements shifted one position to the right.

Note that the last argument of the insert() method is a variable argument, so we can insert any number of items into an array.

Let’s use it to insert three elements in srcArray starting at index two:

int[] destArray = ArrayUtils.insert(2, srcArray, 77, 88, 99);

And the remaining elements will be shifted three places to the right.

Furthermore, this can be achieved trivially for the ArrayList:

anArrayList.add(index, newElement);

ArrayList shifts the elements and inserts the element at the required location.

5. Prepending an Element

By prepending an element to an array, we aim to insert an element at the index 0. Of course, we can solve the problem using our insertAnElementAtAGivenIndex() method:

int[] anArray = { 1, 2, 3, 4 };
int[] expectedArray = { 42, 1, 2, 3, 4 };
int[] result = ArrayOperations.insertAnElementAtAGivenIndex(anArray, 0, 42);
 
assertThat(result).containsExactly(expectedArray);

Alternatively, we can use the System.arraycopy() method to avoid the shifting operations:

public static int[] prependAnElementToArray(int[] srcArray, int element) {
    int[] newArray = new int[srcArray.length + 1];
    newArray[0] = element;
    System.arraycopy(srcArray, 0, newArray, 1, srcArray.length);
 
    return newArray;
}

Next, let’s test this method using the same input:

int[] anArray = { 1, 2, 3, 4 };
int[] expectedArray = { 42, 1, 2, 3, 4 };
int[] result = ArrayOperations.prependAnElementToArray(anArray,  42);
 
assertThat(result).containsExactly(expectedArray);

Additionally, the ArrayUtils.addFirst() method from Apache Commons Lang 3 can solve the problem straightforwardly:

int[] anArray = { 1, 2, 3, 4 };
int[] expectedArray = { 42, 1, 2, 3, 4 };
int[] result = ArrayUtils.addFirst(anArray, 42);
 
assertThat(result).containsExactly(expectedArray);

It’s worth noting that if the given array isn’t null, ArrayUtils.addFirst() internally invokes ArrayUtils.insert() to insert the desired element at index 0.

Conversely, if we want to add an element to an ArrayList, we can still use the ArrayList.add() method and pass 0 as the index: anArrayList.add(0, newElement).

6. Conclusion

In this article, we looked at Java array and ArrayList. Furthermore, we looked at the similarities and differences between the two. Finally, we saw how to append and insert elements in an array and ArrayList.

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)