Initializing Arrays In Java

May 08, 2022
java initialize array with values

Overview

Java offers a variety of data structures for developers to work with. One such data structure is the Array. An Array is a collection of data objects consisting of the same data type. It is one of the most fundamental data structures in Java and is used for implementing almost every type of algorithm.

In this article, we will be discussing how to use Arrays in Java. Along with exploring a way to declare an Array, we will mainly be discussing various methods used to initialize an Array with values in Java.

Introduction to Arrays

The values stored in the Array are referred to as elements. Each element has a unique index value that is used to access the data stored in them. The only limitation in the Array is of size. The size of an Array is fixed. It is initially set when an Array is declared and after that, it cannot be altered.

explore new Java roles

Declaring an Array in Java

An Array is declared in a very similar way to other variables are declared. It is done by providing an identifier (name) and the data type. The additional part is the addition of rectangular brackets [] to denote that it is an Array.

 

Following are the two basic ways to declare an Array:

int myArr [];

int[] myArr;

Both ways are valid but the first method is more commonly used.

You must have noticed that the size of the Array is not mentioned in the declaration process. It is because here only an Array reference is created in the memory. This is where a memory address is just assigned to the Array. It can be considered as the address of the Array in the memory.

Initialize an Array in Java

After a declaration, the Array has to be initialized just like any other variables. As an Array consists of multiple values, its initialization process is not as simple as a variable. The Array initialization process includes assigning an initial value to every element in the Array.

Initializing an Array with default values

To initialize an Array with default values in Java, the new keyword is used with the data type of the Array The size of the Array is then placed in the rectangular brackets.

int[] myArr = new int[10];

The code line above initializes an Array of Size 10. This initialization approach can be considered as an extension of the declaration method mentioned before as the Array is also declared here along with initialization.

You must have noticed that no values are included. This is because every element in the Array will be automatically initialized with the default value. Java by default, initialize the Array with pre-defined values depending on the element data type. For instance, an Integer Array is initialized with 0 in every element, the Boolean Array would be initialized with False and the string type Array is initialized with empty strings.

Initializing an Array with non-default values

If a program requires to initialize an Array with specific values instead of default ones, it can be done by assigning the values one at a time.

 

See this code snippet below:

int[] myArr = new int[5];

intArray[0] = 3;

intArray[1] = 12;

intArray[2] = 45;

intArray[3] = 23;

intArray[4] = 11;

A small integer Array of size 5 is first declared in the code above and 5 non-default values are assigned in it. This is a significantly slower method to initialize the Array with values of your choice, especially when you would have to initialize an Array of a relatively bigger size. Imagine assigning one by one values to an Array of size 1000. It can only be a good option when you have an Array of very limited size and the values to be assigned are very distinct.

Initialize an Array using Curly braces { }

This is the most commonly used way to initialize an Array with default as well as non-default values. It also allows you to declare and initialize the Array simultaneously with the use of curly brackets { }.  All the values to be assigned in the Array has to be written inside the curly brackets, separated by a comma.

 

The following code demonstrate the use of curly braces to initialize an integer Array with 45, 55, 95 and 105:

int myArr [] = {45, 55, 95, 105};

Here the square brackets are left empty because the size of the Array will be determined by the number of elements specified inside the curly brackets. In this case, the size of the Array will be 4. This method can be used for all data types including Boolean, char, byte as well as objects.

 

See this code below where an Array of string data types is simultaneously declared and initialized with 3 values,

String[] myStrArr = {"hello", "world”, “Java”};

Initialization using stream Interface

An unconventional approach to initialize an Array is by generating a stream of values and then assigning it to the Array. It includes the use of multiple IntStream interfaces mentioned in the below example.

 

See the code demonstration below showing the initializing of an integer Array of size 20 using three IntStream methods:

int[] myArr = IntStream.range(1, 21).toArray();

int[] myArr = IntStream.rangeClosed(1, 20).toArray();

int[] myArr = IntStream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20).toArray();

· IntStream.range()

while declaring and initializing an Array of integers using streams, the IntStream Java interface is used to create the Array,

int[] myArr = IntStream.range(1, 21).toArray();

 

This code creates an Array of 20 integers, containing the numbers from 1 to 20:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

The range() method is used here that takes the start and end of the data sequence as parameters. It is to be noted that the second parameter is not included, so you will always have to take 1 value greater than the intended. The method toArray() is then used with it that convert the range to an Array.

· IntStream.rangeClosed()

Although it is not necessary but If you want to include the last element of the range, IntStream.rangeClosed() method can be used instead of range() method:

int[] myArr = IntStream.rangeClosed(1, 20).toArray();

 

This statement will produce an Array of exact 20 integers, from 1 to 20:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

· IntStream.of()

The IntStream.of() method function is very similar to using curly braces. The elements are assigned in the of() method like this,

int[] myArr = IntStream.of(34, 23, 14, 65, 12).toArray();

 

This will produce the following Array,

[34, 23, 14, 65, 12]

 

The .of() method can also be integrated with the sorted() method, to sort the Array as it is initialized:

int[] myArr = IntStream.of(34, 23, 14, 65, 12).sorted().toArray();

 

This will result in the same Array but with sorted elements,

[12, 14, 23, 34, 65]

Java initialize Array with values using Loop

One of the best approaches to initialize an Array is by using a FOR loop. Only For loop is used for initialization because it is a count-based loop and can be easily used to iterate the Array by incrementing the counter variable:

 

See this code below where a For loop is used to initialize an Array with values ranging from 0 to 19.

int[] myArr = new int[20];       

for (int x = 0; x < myArr.length; x++) {

      myArr [x] = x;

}

 

The output will be,

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

This same initialization can also be easily done using the previously mentioned techniques but this is because these values are very simple and the Array is also very limited.  initialization with Java is very useful when you have to apply a more complex logic for calculating the value to be assigned in a huge Array. For instance, if you have to initialize an Array of 1000 size with values that are increasing or decreasing at a certain rate, or maybe with factors or multiples of a number.

See Also: 10 differences between Array and ArrayList in Java

Conclusion

In this article, we have covered some basics of the Array and explored multiple approaches to initialize an Array in Java. You can use any of these initialization methods depending on your requirements and the size of the Array.

new Java jobs

author

jordan

Full Stack Java Developer | Writer | Recruiter, bridging the gap between exceptional talent and opportunities, for some of the biggest Fortune 500 companies.


Candidate signup

Create a free profile to start finding your next opportunity.

Sign up to get hired.

Employer signup

Sign up and find your next team member.

Sign up to hire.

How it works

Learn more about Xperti's unique talent matching process.

See how it works.

Join our community

Connect and Engage with Technology Enthusiasts.

Join the community.