Open In App

How to Initialize an Array in Java?

Last Updated : 25 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

An array in Java is a data structure used to store multiple values of the same data type. Each element in an array has a unique index value. It makes it easy to access individual elements. In an array, we have to declare its size first because the size of the array is fixed. In an array, we can store elements of different data types like integer, string, date, etc. In this article, we will discuss different ways to declare and initialize an array in Java.

Declare an Array in Java

In Java, an array is declared by specifying its data type, and identifier, and adding brackets [] to indicate it is an array.

Syntax to Declare an Array

type arrayName [];
type [] arrayName;

  • type: The type of elements the array will hold (e.g., intString).
  • arrayName: The name of an array.

Here, size of the array is not mentioned because a reference of an array is created in the memory. It can be also known as a memory address of an array.

Initialize an Array in Java

After declaring an array we have to initialize it with values as we have to do it with other variables. In an array, we have to assign multiple values, so the initializing process is not as simple as variables. We will cover the different ways to initialize arrays below.

1. Initialize an Array with a Fixed Size and Default Values 

In Java, an array can be initialized by default values when the size of the array is declared with rectangular brackets [ ].

int [] arr = new int[20]; // Array of size 20, initialized with default values (0)

We can specify the size of an array at the time of initialization. When we created this way, each element gets a default value (0 for integers, false for boolean, and null for objects).

2. Initialize an Array with Specific Values

When we know the values and we want to store it, we can initialize the array with specific values directly.

int[] arr = {1, 2, 3, 4, 5}; // Array initialized with specified values

3. Initialize an Array Using Curly Braces { }

An array can also be initialized by using curly braces where we don’t have to declare the size of the array. All the non-default values are initialized in the curly braces which are separated by a comma.

String[] arr = {“Geeks”, “of”, “Geeks”};

In the above example, a string-type array is initialized with non-default values using curly braces.

4. Initialize an Array with non-default values 

In Java, we can also initialize an array with particular values. For that, we need to initialize each value one by one. But this method is only useful for small sizes of arrays not for arrays having large sizes. For large-size arrays, we have to use a loop to initialize non-default values.

int[] arr = new int[4];
arr[0] = 2;
arr[1] = 4;
arr[2] = 6;
arr[3] = 8;

In the above example, an integer type array of size 4 is declared and then 4 non-default values are initialized in it.

5. Initializing an Array Using Loops

We can also use loops to initialize array elements with specific values. This method is specially useful for larger arrays.

Example:

int[] arr = new int[5];

for (int i = 0; i < arr.length; i++) {

arr[i] = i + 1; // Fills array with values 1, 2, 3, 4, 5

}

Using Arrays with Unknown Size

If the size of the array is unknown but we want to fill it dynamically, we can initialize it first with a fixed size and add values later or use a data structure like ArrayList. Some common operations are mentioned below:

Accessing Array Elements Using Index

We can access and manipulate array elements by referring to their index.

int[] arr = {1, 2, 3, 4};

System.out.println(arr[0]); // Output: 1

Using Array Length

We can use the length property to return the number of elements in an array.

int[] arr = {1, 2, 3, 4};

System.out.println(“Array length: ” + arr.length); // Output: 4

Advanced Initialization Using Streams

An array can be initialized by using a stream interface. The IntStream interface in Java offers additional ways to initialize arrays with sequential or predefined values. Below are three instream interfaces that are used to initialize an integer type array.

1. Using IntStream.range()

It is used to initialize an array of integers within a given range.

  • The first parameter is the starting element.
  • And the second parameter defines the upper limit (exclusive).
  • It means the array will include elements greater than or equal to the first parameter but less than the second one.

Example:

int[] arr1 = java.util.stream.IntStream.range(1, 5).toArray();

// Output: 1 2 3 4

2. Using IntStream.rangeClosed()

It creates an array within a range (inclusive of the end).

Example:

int[] arr2 = java.util.stream.IntStream.rangeClosed(1, 4).toArray();

// Output: 1 2 3 4

3. Using IntStream.of()

It directly initializes an array with specified values.

Example:

int[] arr3 = java.util.stream.IntStream.of(1, 2, 3, 4).toArray();

// Output: 1 2 3 4

Example Program

Below is a simple program demonstrating different ways of initializing an array.

// Java program to demonstrate different ways of
// initializing an integer array

import java.util.stream.IntStream;

public class Main {
 
    public static void main(String[] args) {

        // an array of integers using IntStream.range()
        // method
        int[] arr1 = IntStream.range(1, 5).toArray();
        for (int i = 0; i < arr1.length; i++) {
            System.out.print(arr1[i] + " ");
        }

        System.out.print('\n');

        // an array of integers using
        // IntStream.rangeClosed() method
        int[] arr2 = IntStream.rangeClosed(1, 4).toArray();
        for (int i = 0; i < arr2.length; i++) {
            System.out.print(arr2[i] + " ");
        }

        System.out.print('\n');

        // an array of integers using IntStream.of()
        // method
        int[] arr3 = IntStream.of(1, 2, 3, 4).toArray();
        for (int i = 0; i < arr3.length; i++) {
            System.out.print(arr3[i] + " ");
        }
    }
}

Output
1 2 3 4 
1 2 3 4 
1 2 3 4 


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg