Home Java How to initialize an array in Java

How to initialize an array in Java

An array is a group of similar typed variables that are referred to by a common. In other words, we can define it as a contiguous memory location that stores data of the same type. Arrays offer a convenient means of grouping data items.

The purpose of using arrays is that they come with some of the advantages, which include: In an array, memory is allocated dynamically, and this results in saving of memory. This memory can also be allocated at run time. An array is cache-friendly hence easily accessible.

In this tutorial, we are going to discuss the various methods we use to initialize an array. Before that, let’s have a brief understanding of the syntax of an array and its types so that when we initialize the array. This will make it easy for us to figure out which type of array we are initializing.

Types of array

There are two types of array:

  • One-dimensional array – Specifying the position with a single index value that allows elements to be accessed individually. Its size is fixed.
  • Two-dimensional array – This a 2D array organized as a matrix. It is represented as a collection of rows and columns.

Declaration of an array

One-dimensional array

Return_type [] array_name;
        or
Return_type array_name[];

Example:

Int score [];   or  int [] score  or String []name;

Two-dimensional

Return_type [][] array_name;
        or
Return_type array_name[][];

Example:

String student [] [];   or double results [] []; or String [] [] name;

From the above examples, ‘return_type’ specifies the type of data elements in the array. This may include; String, double, int, etc. The ‘array_name’ specifies the name given to the array. For example, ‘student’ is the name of our array.

Initializing an array means giving it a value for it to store data. For instance, initializing an array of students will involve adding students to the array.

Syntax
return_type array_name[] = new array_name[size]

There are different ways of initializing an array. Let’s now jump in and discuss these several ways

Initializing an array after the declaration

We can declare our array globally and initialize it at the time of need. This case is best used when you have not yet determined what values you need to store in the array. In this case, you will first declare your array, then later in the code. You can initialize the array. We will use the keyword ‘new’ during initialization.

class Student {
    public static void main( String args[] ) {
        String student [];
      //initializing the array
        student = new String[]{ "Moses", "Jeff", "Mary", "Noah", "Skoda" };
        //Printing the elements of array
        for (int p =0;p < 5;p++)
        {
            System.out.println(student[i]);
        }
    }
}

Initialization at the time of declaration

We can also initialize the array at the point of declaration. In this case, we do not specify the size of the array since we know the values we want to store in the array.

Example: Suppose we need to declare an array to store 5 known names of students. We can do this at the time of declaration since the names are known.

class Student {
    public static void main( String args[] ) {
        
      String student[] = { "Moses", "Jeff", "Mary", "Noah", "Skoda" };
       
    }
}

Initializing one element at a time using for loop

As an array may hold more than one element, we can decide to initialize all the elements at once or one element at a time. Below is an example of the initialization of one element at a time using a for a loop.

//one-dimensional array
for (int p = 0; p < array.length; p++) {
    array[p] = p + 2;
}
//two-dimensional array

for (int p = 0; p < 2; p++) {
    for (int k = 0; k < 5; k++) {
        array[p][k] = k + 1;
    }
}

Using Array.fill()

This is a java class in the ‘java.Utils.Arrays’. This method assigns a specified value to each element in the array. In the example below, all the array values are assigned to a value of 2.

int num[] = new int[5];
Arrays.fill(num, 2);
System.out.println(Arrays.toString(num)); 

Using Arrays.copyOf()

This also another interesting method to initialize an array. This method copies another array and creates a new array from the copy. A few points to note about this method, at times, it might throw a ‘NullPointerException’ when the source array is not initialized. Lastly, it can throw a ‘NegativeArraySizeException’ error when the source array length is negative.

int array[] = { 1, 2, 3, 4, 5 };
int[] copy = Arrays.copyOf(array, 5);

Using Array.setAll()

This method was introduced on Java 8. It sets all elements of the specified array using a generator function. If the generator function is null, then a ‘NullPointerException‘ error is thrown. For instance, let’s use this method to set all elements to their respective index on an array of size 5.

int[] array = new int[5];
Arrays.setAll(array, p -> p);
System.out.println(Arrays.toString(array));
// [0, 1, 2, 3, 4,]

Conclusion

Arrays store data of the same type, for instance, an array to store a list of names of students studying a similar unit. Before working on these arrays, you must declare the array and then initialize it. Initialization is simply adding data to the array. In this tutorial, we have covered these various methods of array initialization. To get more on array, check out ArrayList in Java with examples here.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More