Java

How to Create an Array in Java

Arrays are collections of similar data types such as int, string, etc., and can store multiple values in a single variable. For example, if we have to store the names of hundred employees of a company, then instead of storing their names in separate variables, it will be preferred to store them in an array. Each name will be stored within the same array but at a different index.

Before heading towards array creation, we first need to understand what an array is and why we should use an array in java? So, in this regard, this write-up will cover the below-listed concepts of arrays:

So, let’s begin!

What is an Array in Java

A data structure that can store multiple elements of the same data type is known as an array in java. In arrays, each element/value is stored at a different index. In java arrays, indexes are the numeric values that determine the element’s location in an array. The indexing of the java arrays starts from zero.

Why Arrays

The main reason to use arrays in any programming language is that they allow multiple elements/values to be stored in a single variable and with a single name. Therefore, creating a separate variable for each array element is not needed in arrays.

How to Declare an Array in Java

To create an array, we have to follow one of the below-given syntaxes:

dataType[] arrayName;

Firstly, we have to specify the data type(e.g. int, float, etc.) followed by square brackets [ ], and then comes the user-specified array name.

The second way to declare an array is shown in the following snippet:

dataType arrayName[];

This time array name will come prior to the square brackets i.e. data type, then the user-specified array name followed by square brackets.

How to instantiate an Array in Java

When we create an array only the reference of the array is created hence at the time of array declaration we can’t specify the array size, if we do so, we will encounter a compile-time error as shown below:

So, how to specify the array size in java? Well! We can do so with the help of a “new” operator/keyword as shown in the below snippet:

This is how we can allocate the memory to an array with the help of a new operator in java.

How to Declare and Instantiate an Array in One Step

We can initialize an array at the time of array declaration, and to do so, we need to follow the following syntax:

dataType[] arrayName= new dataType[arraySize];

The below snippet will provide you more clarity about this concept:

The above snippet teaches us that the data type must be the same on each side. Moreover, int[15] represents that it is an integer type array of size 15.

How to initialize an Array in Java

As of now, we have learned how to create an array and how to allocate memory to an array? Now, it’s time to understand how to initialize the values to an array? And to do so, we have to follow one of the below-given syntaxes:

Syntax 1

To initialize an array, we can specify a list of comma-separated values within curly brackets as shown in the below snippet:

dataType[] arrayName = {value1, value2, value3, ...};

In this way, we can insert values to an array.

Syntax 2

Or we can specify the values to the array indexes individually as shown in the below snippet:

arrayName[arrayIndex0] = value1;

arrayName[arrayIndex1] = value2;

arrayName[arrayIndex2] = value3;

...

Let’s consider the below snippet for the clarity of concept:

In this way, we can initialize the values to the specific indexes of an array.

How to Declare, Instantiate, and Initialize an Array in One Step

We can achieve all three functionalities in one go as shown in the below snippet:

dataType[] arrayName = {value1, value2, value3, ... };

In this way can skip the array instantiation step.

How to Access Array Elements

We can access an individual value of an array using the following syntax:

arrayName[arrayIndex];

To access the whole array elements, we can utilize a loop as shown in the below snippet:

for (dataType variable; condition; increment/decrement)

{

arrayName[variable];

}

Now let’s consider an example, for a profound understanding of how to create, instantiate, initialize, and access array elements.

How to create a string type array

In the below snippet, we will create a string type array and initialize it with five values:

public class ArrayExample {
  public static void main(String[] args) {
      String[] myArray = {"Java", "JavaScript", "PHP", "Python", "C++"};
      System.out.println("Value Present at Third Index: " + myArray[2]);


      for (inti=0; i<5; i++)
      {
       System.out.println("Value at index " + i + ": " + myArray[i]);
      }
    }
}

In the above snippet, firstly, we created and initialized an array. Next, we accessed the third element of the array and printed it. As the loop starts from the 0th index, therefore, we specified myArray[2] to access the third element. Finally, we utilized a for-loop to access and print all the array's values. The below snippet will show the desired output:

The output verifies the array creation.

Conclusion

To create an array in java, we have to specify the data type(e.g. int, float, etc.) followed by square brackets [ ], and finally, the user-specified array name. At the time of array creation, only the reference of the array is created, and to allocate the memory to the array we have to utilize the “new” operator. To initialize an array, a list of comma-separated values can be specified within curly brackets. This write-up explained various aspects of java arrays such as array creation, instantiation, and initialization.

About the author

Anees Asghar

I am a self-motivated IT professional having more than one year of industry experience in technical writing. I am passionate about writing on the topics related to web development.