How to Declare and Initialize an Array in Java

Introduction

In this tutorial, we'll take a look at how to declare and initialize arrays in Java.

We declare an array in Java as we do other variables, by providing a type and name:

int[] myArray;

To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax:

int[] myArray = {13, 14, 15};

Or, you could generate a stream of values and assign it back to the array:

int[] intArray = IntStream.range(1, 11).toArray();
int[] intArray = IntStream.rangeClosed(1, 10).toArray();
int[] intArray = IntStream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).toArray();

To understand how this works, read more to learn the ins and outs of array declaration and instantiation!

Array Declaration in Java

The declaration of an array object in Java follows the same logic as declaring a Java variable. We identify the data type of the array elements, and the name of the variable, while adding rectangular brackets [] to denote its an array.

Here are two valid ways to declare an array:

int intArray[];
int[] intArray;

The second option is oftentimes preferred, as it more clearly denotes of which type intArray is.

Note that we've only created an array reference. No memory has been allocated to the array as the size is unknown, and we can't do much with it.

Array Initialization in Java

To use the array, we can initialize it with the new keyword, followed by the data type of our array, and rectangular brackets containing its size:

int[] intArray = new int[10];

This allocates the memory for an array of size 10. This size is immutable.

Java populates our array with default values depending on the element type - 0 for integers, false for booleans, null for objects, etc. Let's see more of how we can instantiate an array with values we want.

The slow way to initialize your array with non-default values is to assign values one by one:

int[] intArray = new int[10];
intArray[0] = 22;

In this case, you declared an integer array object containing 10 elements, so you can initialize each element using its index value.

The most common and convenient strategy is to declare and initialize the array simultaneously with curly brackets {} containing the elements of our array.

The following code initializes an integer array with three elements - 13, 14, and 15:

int intArray[] = {13, 14, 15};

Keep in mind that the size of your array object will be the number of elements you specify inside the curly brackets. Therefore, that array object is of size three.

This method work for objects as well. If we wanted to initialize an array of three Strings, we would do it like this:

int[] stringArray = {"zelda", "link", "ganon"};

Java allows us to initialize the array using the new keyword as well:

int[] intArray = new int[]{13, 14, 15};
int[] stringArray = new String[]{"zelda", "link", "ganon"};

It works the same way.

Note: If you're creating a method that returns an initialized array, you will have to use the new keyword with the curly braces. When returning an array in a method, curly braces alone won't work:

public String[] getNames() {
    return new String[]{"zelda", "link", "ganon"}; // Works
}

public String[] getNames() {
    return {"zelda", "link", "ganon"}; // Doesn't work
}

IntStream.range()

If you're declaring and initializing an array of integers, you may opt to use the IntStream Java interface:

int[] intArray = IntStream.range(1, 11).toArray();

The above code creates an array of ten integers, containing the numbers 1 to 10:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

The IntStream interface has a range() method that takes the beginning and the end of our sequence as parameters. Keep in mind that the second parameter is not included, while the first is.

We then use the method toArray() method to convert it to an array.

Note: IntStream is just one of few classes that can be used to create ranges. You can also use a DoubleStream or LongStream in any of these examples instead.

IntStream.rangeClosed()

If you'd like to override that characteristic, and include the last element as well, you can use IntStream.rangeClosed() instead:

int[] intArray = IntStream.rangeClosed(1, 10).toArray();

This produces an array of ten integers, from 1 to 10:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

IntStream.of()

The IntStream.of() method functions very similarly to declaring an array with some set number of values, such as:

int[] intArray = new int[]{6, 2, 4, 5, 7};

Here, we specify the elements in the of() call:

int[] intArray = IntStream.of(6, 2, 4, 5, 7).toArray();

This produces an array with the order of elements preserved:

[6, 2, 4, 5, 7]

Or, you could even call the sorted() method on this, to sort the array as it's being initialized:

int[] intArray = IntStream.of(6, 2, 4, 5, 7).sorted().toArray();

Which results in an array with this order of elements:

[2, 4, 5, 6, 7]

Java Array Loop Initialization

One of the most powerful techniques that you can use to initialize your array involves using a for loop to initialize it with some values.

Let's use a loop to initialize an integer array with values 0 to 9:

int[] intAray = new int[10];	

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

This is identical to any of the following, shorter options:

int[] intArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] intArray = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] intArray = IntStream.rangeClosed(0, 9).toArray();

A loop is more ideal than the other methods when you have more complex logic to determine the value of the array element.

For example, with a for loop we can do things like making elements at even indices twice as large:

int[] intArray = new int[10];	

for (int i = 0; i < intArray.length; i++) {
    if (i % 2 == 0) {
        int_array[i] = i * 2;
    } else {
        int_array[i] = i;
    }
}

Conclusion

In this article, we discovered the different ways and methods you can follow to declare and initialize an array in Java. We've used curly braces {}, the new keyword and for loops to initialize arrays in Java, so that you have many options for different situations!

We've also covered a few ways to use the IntStream class to populate arrays with ranges of elements.

Author image
Agadir, Morocco Twitter
I am a very curious individual. Learning is my drive in life and technology is the language I speak. I enjoy the beauty of computer science and the art of programming.