Advertise with us

Search Mastertheboss

Our eBooks

4 ways to initialize an Array in Java

This article discusses about array initialization in Java, showing multiple ways to initialize an Array, some of them you probably don't know!

Basic Array Initialization in Java

First of all, let's learn how to declare an Array:

String array[];

So you basically specify the datatype and the declared variable name. Mind it, declaring an array does not initialize it. You can initialize an array, and assign memory to it, by providing just the array size or also the content of the array.

Initialize an array specifing the array size:

	String array[] = new String[2];

Initialize an array with its content using Array Literal:

	String array[] = new String[] { "Pear", "Apple", "Banana" };

You can of course also split the declaration from the assignment:

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

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

how to initialize array in java

Therefore, you can retrieve it by id as follows:

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

Also, if you don't need to retrieve the array by 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);

Initialize an array in Java 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.

Example:

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.

Initialize an array in Java using Arrays.setAll()

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));

Initialize an array in Java 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.

In this tutorial we have covered four basic strategies to intialize an array in Java.

© 2020 mastertheboss.com. All Rights Reserved.

Please publish modules in offcanvas position.