Java Basics

How to initialize an array in Java?

Last updated on October 21, 2018 by Michael Lossagk , 9 min  • 
How to initialize an array in Java?

1. Initialization at time of declaration


Arrays can be initialized directly at the time of declaration. This can be done in different ways, which I will describe in the following sections.

1.1 Primitive types


The initialization of arrays with primitive types using the example of integers.

On the left side you first write the type, in this case int, followed by square brackets [] and the variable name.

int[] myIntArray;

The square brackets are decisive here, that the declaration is an array.

Likewise, the following notation is a valid syntax:

int myIntArray[];

however, the first syntax described is the generally accepted convention, which is why it is used in the following examples.

1.1.1 Initialization via new int[]


To initialize the array via int [] we can write:

int[] myIntArray1 = new int[3]; // myIntArray1 = [0, 0, 0]

Here an integer array is generated which contains space for 3 values ​​(indices 0, 1, 2) and is filled with zeros initially.

1.1.2 Initialization via new int[]{}


To initialize the array via int []{} we can write the following:

int[] myIntArray2 = new int[]{1, 2, 3}; // myIntArray2 = [1, 2, 3]

Here an integer array is generated which contains space for 3 values ​​(indices 0, 1, 2) and is initially filled with the values ​​1,2 and 3. Note that unlike the previous example, the size of the array is not written in the square brackets. Adding the number additionally would cause a compiler error, as this is not a correct syntax.

1.1.2 Initialization via {}


To initialize the array via {} we can write the following:

int[] myIntArray3 = {1, 2, 3}; // myIntArray3 = [1, 2, 3]

Here, as in the previous example, an integer array is generated which contains space for 3 values ​​(indexes 0, 1, 2) and is initially filled with the values ​​1, 2 and 3. It should be noted that in contrast to the previous example, the explicit description with new int [] can be omitted, as the compiler recognizes this from the context and processes it accordingly.

1.2 Complex Types


The initialization of arrays with complex types using the example of strings.

As with the simple data type examples, on the left side you always write the type first, in this case string, followed by square brackets [] and the variable name.

String[] myStringArray;

The square brackets are decisive here, that the declaration is an array. This is as identical as in the examples with the primitive types.

1.2.1 Initialization via new String []


To initialize the array via String [] we can write the following:

String[] myStringArray1 = new String[3]; // myStringArray1 = [null, null, null]

Here, a string array is generated which contains space for 3 values ​​(indices 0, 1, 2) and is initially filled with null. It should be noted that this is not identical to the integer example. In the example with integers, the array was initialized with the numeric value 0, whereas in this example the Java null value is set.

1.2.2 Initialization via new String[]{}


To initialize the array by String []{} we can write the following:

String[] myStringArray2 = new String[]{"a", "b", "c"}; // myStringArray2 = [a, b, c]

Here, a string array is generated which contains space for 3 values ​​(indices 0, 1, 2) and is initially filled with the values ​​a, b and c. Note that unlike the previous example, the size of the array is not written in the square brackets. Adding the number additionally would cause a compiler error, as this is not a correct syntax.

1.2.3 Initialization via {}


To initialize the array via {} we can write the following:

String[] myStringArray3 = {"a", "b", "c"}; // myStringArray3 = [a, b, c]

Here, as in the previous example, a string array is generated which contains space for 3 values ​​(indices 0, 1, 2) and is initially filled with the values ​​1, 2 and 3. It should be noted that in contrast to the previous example, the explicit description with new String [] can be omitted, as the compiler recognizes this from the context and processes it accordingly.

2. Initialization in a loop


Arrays do not have to be initialized directly at the time of declaration. The initialization can also be done at a later time, such as when iterating over a loop, which I will describe in the following sections.

2.1 Primitive types


The following example creates a simple function that expects an integer value and then creates an array and fills it in a loop.

public int[] createArrayWithRange(int rangeNumber) {
    int[] range = new int[rangeNumber];

    for (int i = 1; i <= range.length; ++i) {
        range[i - 1] = i;
    }
    return range;
}
// createArrayWithRange(3) -> [1, 2, 3]

Iterates in the loop from 1 to the specified length and sets the value according to the loop variable i for each loop pass.

2.2 Complex types


The following example expects a string as a parameter. From this string, the length is determined and created a correspondingly large string array. The loop iterates over the length of the array and writes an entry to the appropriate location in the array for each letter of the passed string.

public String[] createArrayWithRange(String str) {
    String[] range = new String[str.length()];

    for (int i = 1; i <= range.length; i++) {
        range[i - 1] = String.valueOf(str.charAt(i-1));
    }
    return range;
}
// createArrayWithRange("Test") -> [T, e, s, t]

If the string Test is passed when the function is called and then the array returned by the function is output again, the result is: [T, e, s, t].

3. Initialization via streams


Since Java 8 there is the possibility to use Streams. The following example shows how to create an array using these streams:

public Integer[] createArrayWithStream(int number) {
    Integer[] range = IntStream.range(0, number)
            .mapToObj(i -> new Integer((int) (Math.random() * number + 1)))
            .toArray(Integer[]::new);
    return range;
}

Here, an integer is expected as a parameter, which determines the size of the array. This is done by using the statement IntStream.range (0, number). Furthermore, the array is filled with random numbers, whereby the interval is limited by the given size. This means that if the number 10 is transferred, then random numbers from 1 to 10 are written into the array. If, for example, the number 5 is passed, the maximum size of a random number is 5, etc. The random number is filled by the array Function mapToObj (i -> new Integer ((int) (Math.random () * number + 1))), where i stands for the loop index and creates a random number for every i and into an integer is converted (cast) new Integer ((int) (Math.random () * number + 1)). The last statement merges it into an integer array toArray (Integer [] :: new).

4. Conclusion


In this tutorial I have shown some ways to initialize an array in Java. Here, a distinction was made between the initialization directly at the declaration and at a later time. In addition, attention was drawn to the differences in initialization with simple and complex data types. Finally, an outlook on the possibilities of the Java Stream API was given and how you can also use this to initialize an array. Find the appropriate code samples in my GitLab repository. If you want to learn more about Java and programming I can recommend you this book.


Michael Lossagk
Michael Lossagk
Coding Enthusiast
Founder @ TechDiffuse

You may also like


Share this: