How to init an Array in Java made simple

In this comprehensive guide, we uncover the diverse techniques to init an array in Java, discussing basic and advanced approaches. Whether you’re diving into static or dynamic array creation, Arrays.copy or exploring data Streaming , this article equips you with the essential know-how to streamline your Java programming experience

Static Array Initialization

Static array initialization refers to the process of assigning values to an array at the time of declaration. When you statically initialize an array in Java, you provide the array elements’ values within braces {} at the point of creating the array.

For example:

String array[] = new String[] { "Pear", "Apple", "Banana" }; 
int[] datas = { 12, 48, 91, 17 }; 
char grade[] = { 'A', 'B', 'C', 'D', 'F' }; 

// Multidimensional Array
float[][] matrixTemp = { { 1.0F, 2.0F, 3.0F }, { 4.0F, 5.0F, 6.0F }}; 
int x = 1, y[] = { 1, 2, 3, 4, 5 }, k = 3;

Dynamic Array Initialization

Unlike static array initialization, where values are provided at the time of declaration, dynamic initialization involves allocating memory for the array first and then setting values to its elements in subsequent steps.

Here’s an example of dynamic array initialization:

int[] numbers = new int[5]; // Allocating memory for 5 elements

numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

When retrieving an array by its index, it is important to remember that index starts from 0:

how to init an array in java

Therefore, you can retrieve it by id as follows:

   for (int i =0;i < 5;i++) {
            System.out.println(array[i]);
   }

On the other hand, if you want to init a multidimensional array in a loop, you need to loop over the array twice. Example:

double[][] temperatures = new double[3][2];

for (int row = 0; row < temperatures.length; row++)
   for (int col = 0; col < temperatures[row].length; col++)
      temperatures[row][col] = Math.random()*100;

Finally, if you don’t need to operate on the array id, you can use the simplified for loop to iterate through the array:

int[] array = new int[]{2,3,5,7,11};

for (int a:array)
   System.out.println(a);

Initialization using Arrays.copyOf()

The java.util.Arrays.copyOf(int[] original,int newLength) method copies the specified array, eventually truncating or padding with zeros (if needed) so the copy has the specified length.

For example, here is how to init an array in Java using Arrays.copyOf:

int[] array = new int[]{2,3,5,7,11};
int[] copy =  Arrays.copyOf(array, 5);

A similar option also exists in the System packages, using the System.arraycopy static method:

int[] src  = new int[]{2,3,5,7,11};
int[] dest = new int[5];
System.arraycopy( src, 0, dest, 0, src.length );

The core difference is that Arrays.copyOf does not just copy elements, it also creates a new array. On the other hand, System.arrayCopy copies into an existing array.

In most cases, System.arrayCopy will be faster because it uses a direct native memory copy. Arrays.copyOf uses Java primitives to copy although the JIT compiler could do some clever special case optimization to improve the performance.

Using Arrays functions to fill an array

The method Arrays.setAll sets all elements of an array using a generator function. This is the most flexible option as it lets you use a Lambda expression to initialize an array using a generator. Example:

int[] arr = new int[10];
Arrays.setAll(arr, (index) -> 1 + index);

This can be useful, for example, to quickly initialize an Array of Objects:

Customer[] customerArray = new Customer[7];
// setting values to customerArray using setAll() method
Arrays.setAll(customerArray, i -> new Customer(i+1, "Index "+i));

A similar function is Arrays.fill which is the best choice if you don’t need to use a generator function but you just need to init the whole array with a value. Here is how to fill an array of 10 int with the value “1”:

int [] myarray = new int[10];
Arrays.fill(myarray, 1);

Finally, if you want to convert a Collection of List objects into an array, you can use the .toArray() method on the Collection. Example:

List<String> list = Arrays.asList("Apple", "Pear", "Banana");
String[] array = list.toArray(new String[list.size()]);

Initialization using the Stream API

Finally, you can also use the Java 8 Stream API for making a copy of an Array into another. Let’s check with at an example:

String[] strArray = {"apple", "tree", "banana'"};
String[] copiedArray = Arrays.stream(strArray).toArray(String[]::new);

Arrays.stream also does a shallow copy of objects, when using non-primitive types.

How to init an Array from a File

Finally, we will show how you can use the java.nio.file.Files Class to read a File in a List of Data. Then, we convert the List into a String array:

// Read the file lines into a List
List<String> lines = Files.lines(Paths.get(fileName));

// Convert the List to an array
String[] linesArray = lines.toArray(new String[lines.size()]);

Printing an Array

To verify the content of a Java Array you don’t need to loop over each item and execute a print statement. By using the do it much faster:

int[] arr = {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(arr));

Here is the output:

how to initialize an array in java

Besides, please note that if you are using a nested array, then you have to use the Arrays.deepToString method instead:

System.out.println(Arrays.deepToString(deepArray));

Conclusion

In this comprehensive guide, we’ve explored the diverse array initialization techniques available in Java, equipping both novice and seasoned programmers with versatile methods to streamline their code creation.

Found the article helpful? if so please follow us on Socials