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.

Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page.

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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 – All Access – NPI EA (cat= Spring)
announcement - icon

All Access is finally out, with all of my Spring courses. Learn JUnit is out as well, and Learn Maven is coming fast. And, of course, quite a bit more affordable. Finally.

>> GET THE COURSE
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 – LambdaTest – NPI EA (cat=Testing)
announcement - icon

End-to-end testing is a very useful method to make sure that your application works as intended. This highlights issues in the overall functionality of the software, that the unit and integration test stages may miss.

Playwright is an easy-to-use, but powerful tool that automates end-to-end testing, and supports all modern browsers and platforms.

When coupled with LambdaTest (an AI-powered cloud-based test execution platform) it can be further scaled to run the Playwright scripts in parallel across 3000+ browser and device combinations:

>> Automated End-to-End Testing With Playwright

Course – Spring Sale 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

Course – Spring Sale 2025 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

1. Introduction

In this tutorial, we’ll deep dive into a core concept in the Java language – arrays.

We’ll first see what’s an array, then how to use them; overall, we’ll cover how to:

  • Get started with arrays
  • Read and write arrays elements
  • Loop over an array
  • Transform arrays into other objects like List or Streams
  • Sort, search and combine arrays

2. What’s an Array?

First things first, we need to define what’s an array? According to the Java documentation, an array is an object containing a fixed number of values of the same type. The elements of an array are indexed, which means we can access them with numbers (called indices).

We can consider an array as a numbered list of cells, each cell being a variable holding a value. In Java, the numbering starts at 0.

There are primitive type arrays and object type arrays. This means we can use arrays of int, float, boolean, … But also arrays of String, Object and custom types as well.

3. Setting up an Array

Now that arrays are well-defined, let’s dive into their usages.

We’ll cover a lot of topics teaching us how to use arrays. We’ll learn some basics like how to declare and initialize an array, but we’ll also cover more advanced subjects like sorting and searching arrays.

Let’s go first with declaration and initialization.

3.1. Declaration

We’ll begin with the declaration. There are two ways to declare an array in Java:

int[] anArray;

or:

int anOtherArray[];

The former is more widely used than the latter.

3.2. Initialization

Now that it’s time to see how to initialize arrays. Again there are multiple ways to initialize an array. We’ll see the main ones here, but this article covers arrays initialization in detail.

Let’s begin with a simple way:

int[] anArray = new int[10];

By using this method, we initialized an array of ten int elements. Note that we need to specify the size of the array.

When using this method, we initialize each element to its default value, here 0. When initializing an array of Object, elements are null by default.

We’ll now see another way giving us the possibility to set values to the array directly when creating it:

int[] anArray = new int[] {1, 2, 3, 4, 5};

Here, we initialized a five element array containing numbers 1 to 5. When using this method we don’t need to specify the length of the array, it’s the number of elements then declared between the braces.

4. The Length of an Array

The length of an array indicates the number of elements in the array and is established when the array is created. After creation, the length is fixed and cannot be changed.

Java provides the built-in property length that can be used to determine the length of an array. This property is available for all array types and returns the number of elements in the array:

int[] anArray = new int[] { 1, 2, 3, 4, 5 };
System.out.println("anArray's length: " + anArray.length);

The above code produces this output:

anArray's length: 5

In addition to using the length property to determine the size of an array, we can also use the Array.getLength() method from the java.lang.reflect.Array class: 

System.out.println("[Array.getLength()] anArray's length: " + Array.getLength(anArray));

This println() method prints:

[Array.getLength()] anArray's length: 5

Array.getLength() accepts the parameter in Object type. It’s useful in scenarios where the array is being handled in a generic or reflective context, such as when we don’t have an array type at compile time.

Next, let’s see an example:

Object arrayAsObj = anArray;
System.out.println("the array Object (anArray) 's length: " + Array.getLength(arrayAsObj));

//output:
the array Object (anArray) 's length: 5  

As the example shows, Array.getLength() allows us to determine the length of any array object without casting it to a specific type.

5. Accessing Elements

Let’s now see how to access the elements of an array. We can achieve this by requiring an array cell position.

For example, this little code snippet will print 10 to the console:

anArray[0] = 10;
System.out.println(anArray[0]);

Note how we are using indices to access the array cells. The number between the brackets is the specific position of the array we want to access.

When accessing a cell, if the passed index is negative or goes beyond the last cell, Java will throw an ArrayIndexOutOfBoundException.

We should be careful then not to use a negative index, or an index greater than or equal to the array size.

6. Iterating Over an Array

Accessing elements one by one can be useful, but we might want to iterate through an array. Let’s see how we can achieve this.

The first way is to use the for loop:

int[] anArray = new int[] {1, 2, 3, 4, 5};
for (int i = 0; i < anArray.length; i++) {
    System.out.println(anArray[i]);
}

This should print numbers 1 to 5 to the console. As we can see we made use of the length property. This is a public property giving us the size of the array.

Of course, it’s possible to use other loop mechanisms such as while or do while. But, as for Java collections, it’s possible to loop over arrays using the foreach loop:

int[] anArray = new int[] {1, 2, 3, 4, 5};
for (int element : anArray) {
    System.out.println(element);
}

This example is equivalent to the previous one, but we got rid of the indices boilerplate code. The foreach loop is an option when:

  • we don’t need to modify the array (putting another value in an element won’t modify the element in the array)
  • we don’t need the indices to do something else

7. Varargs

We’ve already covered the basics when it comes to the creation and manipulation of arrays. Now, we’ll dive into more advanced topics, beginning with varargs. As a reminder, varargs are used to pass an arbitrary number of arguments to a method:

void varargsMethod(String... varargs) {}

This method could take from 0 to an arbitrary number of String arguments. An article covering varargs can be found here.

What we have to know here is that inside the method body, a varargs parameter turns into an array. But, we can also pass an array directly as the argument. Let’s see how by reusing the example method declared above:

String[] anArray = new String[] {"Milk", "Tomato", "Chips"};
varargsMethod(anArray);

Will behave the same as:

varargsMethod("Milk", "Tomato", "Chips");

8. Transforming an Array into a List

Arrays are great, but sometimes it can be handier to deal with List instead. We’ll see here how to transform an array into a List.

We’ll first do it the naïve way, by creating an empty list and iterating over the array to add its elements to the list:

int[] anArray = new int[] {1, 2, 3, 4, 5};

List<Integer> aList = new ArrayList<>();
for (int element : anArray) {
    aList.add(element);
}

But there is another way, a little bit more succinct:

Integer[] anArray = new Integer[] {1, 2, 3, 4, 5};
List<Integer> aList = Arrays.asList(anArray);

The static method Arrays.asList takes a varargs argument and creates a list with the passed values. Unfortunately, this method comes with some drawbacks:

  • It’s not possible to use an array of primitive types
  • We can’t add or remove elements from the created list, as it’ll throw an UnsupportedOperationException

9. From an Array to a Stream

We can now transform arrays into lists, but since Java 8 we have access to the Stream API and we might want to turn our arrays into Stream. Java provides us with the Arrays.stream method for that:

String[] anArray = new String[] {"Milk", "Tomato", "Chips"};
Stream<String> aStream = Arrays.stream(anArray);

When passing an Object array to the method it will return a Stream of the matching type (e.g. Stream<Integer> for an array of Integer). When passing a primitive one it will return the corresponding primitive Stream.

It’s also possible to create the stream only on a subset of the array:

Stream<String> anotherStream = Arrays.stream(anArray, 1, 3);

This will create a Stream<String> with only “Tomato” and “Chips” Strings (the first index being inclusive while the second one is exclusive).

10. Sorting Arrays

Let’s now see how to sort an array, that is rearranging its elements in a certain order. The Arrays class provides us with the sort method. A bit like the stream method, sort has a lot of overloadings.

There are overloadings to sort:

  • Primitive type arrays: which are sorted in ascending order
  • Object arrays (those Object must implement the Comparable interface): which are sorted according to the natural order (relying on the compareTo method from Comparable)
  • Generic arrays: which are sorted according to a given Comparator

In addition, it’s possible to sort only a specific portion of an array (passing start and end indices to the method).

The algorithms behind the sort method are quick sort and merge sort for primitive and other arrays, respectively.

Let’s see how this all work through some examples:

int[] anArray = new int[] {5, 2, 1, 4, 8};
Arrays.sort(anArray); // anArray is now {1, 2, 4, 5, 8}

Integer[] anotherArray = new Integer[] {5, 2, 1, 4, 8};
Arrays.sort(anotherArray); // anotherArray is now {1, 2, 4, 5, 8}

String[] yetAnotherArray = new String[] {"A", "E", "Z", "B", "C"};
Arrays.sort(yetAnotherArray, 1, 3, 
  Comparator.comparing(String::toString).reversed()); // yetAnotherArray is now {"A", "Z", "E", "B", "C"}

Searching an array is pretty simple, we can loop over the array and search our element among the array elements:

int[] anArray = new int[] {5, 2, 1, 4, 8};
for (int i = 0; i < anArray.length; i++) {
    if (anArray[i] == 4) {
        System.out.println("Found at index " + i);
        break;
    }
}

Here we searched for number 4 and found it at index 3.

If we have a sorted array though, we can use another solution: the binary search. The principle of binary search is explained in this article.

Fortunately, Java provides us with the Arrays.binarySearch method. We have to give it an array and an element to search.

In case of a generic array, we also have to give it the Comparator that was used to sort the array in the first place. There is again the possibility to call the method on a subset of the array.

Let’s see an example of the binary search method usage:

int[] anArray = new int[] {1, 2, 3, 4, 5};
int index = Arrays.binarySearch(anArray, 4);
System.out.println("Found at index " + index);

As we stored number 4 in the fourth cell, this will return index 3 as the result. Note that we used an already sorted array.

12. Concatenating Arrays

Finally, let’s see how to concatenate two arrays. The idea is to create an array which length is the sum of the two arrays to concatenate. After that we have to add the elements of the first one and then the elements of the second one:

int[] anArray = new int[] {5, 2, 1, 4, 8};
int[] anotherArray = new int[] {10, 4, 9, 11, 2};

int[] resultArray = new int[anArray.length + anotherArray.length];
for (int i = 0; i < resultArray.length; i++) {
    resultArray[i] = (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length]);
}

As we can see, when the index is still lesser than the first array length we add elements from that array. Then we add elements from the second one. We can make use of the Arrays.setAll method to avoid writing a loop:

int[] anArray = new int[] {5, 2, 1, 4, 8};
int[] anotherArray = new int[] {10, 4, 9, 11, 2};

int[] resultArray = new int[anArray.length + anotherArray.length];
Arrays.setAll(resultArray, i -> (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length]));

This method will set all array element according to the given function. This function associates an index with a result.

Here is a third option to merge to arrays: System.arraycopy. This method takes a source array, a source position, a destination array, a destination position and an int defining the number of elements to copy:

System.arraycopy(anArray, 0, resultArray, 0, anArray.length);
System.arraycopy(anotherArray, 0, resultArray, anArray.length, anotherArray.length);

As we can see, we copy the first array, then the second (after the last element of the first one).

13. Conclusion

In this detailed article we’ve covered basic and some advanced usages of arrays in Java.

We saw that Java offers a lot of methods to deal with arrays through the Arrays utility class. There also are utility classes to manipulate arrays in libraries such as Apache Commons or Guava.

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.

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

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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

Course – Spring Sale 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

Course – Spring Sale 2025 – NPI (All)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

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