Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

How to initialize an array in Java

Understanding arrays is fundamentally important to creating efficient code. Here's how to create them in Java, as well as how to add values to them.

Jul 31, 2024 • 6 Minute Read

Please set an alt value for this image...
  • Software Development
  • Guides

Arrays are a great way to group multiple values together so you can loop over them easily, and keep things logically sorted. However, while arrays are a foundational feature of most programming languages, not all of them have the same syntax and functionality, and Java is no exception.

In this article, I’ll share the primary ways to initialize an array in Java, and the benefits and drawbacks of each. This will prepare you to operate on these arrays as well as build your way to understanding and using the more advanced Collections API.

For those coming in completely unfamiliar with arrays, here’s a quick overview of what they are. If you’re already familiar with the concept, feel free to skip ahead.


Table of contents


What is an array?

An array is a data structure that allows you to group multiple elements of the same type together under a single variable name. Think of a container with a label on it, and within that container you can put many items in a sequential order.

Let’s say you were trying to move house — you’d take your individual books, put them in a box, and then label them something like “novels”, or even “Stephen King books.” You could open this box up and flick through the titles to find the item you’re after. This is far more efficient and easy to work with than, say, leaving your individual books strewn all over the place, which would make them a pain to find and scan through.

Behind the scenes, an array is formed of consecutive blocks of computer memory (known as “contiguous memory”) that holds a specified number of another datatype. But let’s look at what this means in practice. 

For example, you can have an array of integers, like this one:

      int[] testScores = { 93, 84, 65, 70 };
    

Notice the little brackets forming a box-like shape, containing our grouped information. This has been given the name “testScores”, and within it are the values 93, 84, 65, and 70.

You can also have an array of objects, like this one:

      CarPart[] carparts = { new Engine(), new Tires(4), new Headlights(2) }
    

Either way, you can then access them in sequence through a loop or you can look them up individually like so:

      CarPart engine = carparts[0];
    

This is infinitely more elegant than having to find and reference a bunch of individual values, which is why arrays are such a foundational programming concept. 

Now that we’ve got the fundamentals out of the way, let’s talk about how to create an array in Java.

How to initialize an array in Java by size

When you make an array in Java for the first time, you’ve got to declare its size. This is because the array’s size is fixed from the moment you create it. The simplest way to do this is to initialize an empty array of a declared size. Here’s an example:

      int[] temperaturesInApril = new int[30];
    

In the above case, we know that we will need 30 slots for data, one slot for each day in April. Right now, though, the array is just a container filled with empty slots waiting to be filled. How do we get that data in there?

How to add to an array in Java

To add content to your array, just reference the array name, specify the slot in question, and then add the value like so:

      temperaturesInApril[0] = 18;
    

How to initialize an array in Java by content

Say you already know the content you want in your array beforehand, so you want to skip the whole separation of initialization and filling it, and just have it all in one single, elegant line of code. In Java, you can supply said data up-front, and Java will just infer the size, so you don’t even need to specify it.

Here’s an example of that, using a choice selection of soups:

      String[] soupsOfTheDay = { “minestrone”, “broccolli cheese”, “clam chowder” };
    

Java will allocate an array of size 3, since there are three items listed (and make no judgment about you adding broccoli cheese to the menu). To make sure nothing is lost in translation, you can explicitly specify the datatype on both sides of the expression, like this:

      String[] soupsOfTheDay = new String[] { “minestrone”, “broccolli cheese”, “clam chowder” };
    

How to declare an array in Java using C-style initialization

Do you like C languages? If so, you may be more comfortable using C-style syntax to declare your Java arrays, which the language supports. This is because Java was initially positioned as an alternative to C.

For example, the following is equivalent to the previous two statements:

      String soupsOfTheDay[] = { “minestrone”, “broccolli cheese”, “clam chowder” };
    

However, because this syntax is much less common, be aware that you’re probably better off sticking with the Java standard. Why? Because using more commonly recognized syntax will make your code more recognizable, which in turn will make it easier for people to review your work.

How to create a multi-dimensional array in Java

Multi-dimensional arrays, or nested arrays, are basically when you want to have an array of arrays. To go back to our earlier example, it’s like if you put a box inside a box, so you could more easily organize your things. Java has a special syntax for this:

      int[][] battleshipCoordinates = new int[10][10];
    

This creates an array of size 10, with each element holding a nested array of size 10 themselves. 

You can also initialize these by content, like before. Consider this two-dimensional array that declares a grid of spaces for a dungeon game:

      char[][] dungeonMap = // w => wall, e => exit, g => goblin
{
{ ‘w’, ‘w’, ‘e’, ‘w’, ‘w’ },
{ ‘w’, ‘ ’, ‘g’, ‘ ’, ‘w’ },
  …
};

    

Note that for the above to work, each sub-array needs to be of the same length.

How to add to an array in Java

An array’s size is fixed, and can’t change after being initialized. However, you can work around this by initializing a new array of a different size, and simply copying the old values over. This way, you’ve got the old values in the array of your desired size, effectively “growing” it.

To use our handy box example, you couldn’t make a cardboard box larger—it’s already manufactured at that size, and it was built to always fit that set amount. However, you could quite easily get a larger box, and then transfer the contents from the smaller one to the bigger one. 

Here’s an example of that in practice. Let’s say that I have an array of 30 students:

      Student[] students = new Student[] { … }; // 30 total
    

Then, I get one more student. I can’t add them in because the array is already full. As mentioned earlier, we can create a new one and copy everything over, like so:

      Student[] updated = new Student[31];
System.arraycopy(students, 0, updated, 0, students.length);
updated[30] = new Student(“Phillip”);
students = updated;
    

Looks quite cumbersome, right? It is! And just think, you’ve got to do this again for removal when a student leaves the class.

How to create dynamic arrays in Java

If you want to add and remove things from an array, you’ll want to create a dynamic array, which will allow you to do this. You can do this by taking a look at Java’s Collections API, which frees you of the burden of knowing the array’s size from the beginning, and having to re-initialize the array over and over when you add or remove items from it.

Conclusion

Hopefully after reading this, you’ve got a good grasp of how to initialize arrays in Java, and how you can use each case depending on whether or not you know the values yet you’ll be working with.


Further learning

If you found this article helpful why not check out Pluralsight's dedicated learning paths on Java? Written for tech professionals, by tech professionals, each pathway is scaled so you can start at your current proficiency level. Here are some suggestions:

If you're interested in Java, you may also want to check out these resources on the Spring framwork, an open-source framework for building robust and scalable Java applications. Pluralsight offers path on core Spring as well as Spring Security.

Josh Cummings

Josh C.

Like many software craftsmen, Josh eats, sleeps, and dreams in code. He codes for fun, and his kids code for fun! Right now, Josh works as a full-time committer on Spring Security and loves every minute. Application Security holds a special place in his heart, a place diametrically opposed to and cosmically distant from his unending hatred for checked exceptions.

More about this author