How to Initialize an Array in Java

Rajat Hardy
Written by
Last update:

An array is a Java programming keyword that represents a list of values in a single continuous block of memory. When you create an array, the values that you specify are the initial values of the array because they are set when the array is created.

There’s more than one way to create an array. There are two ways to initialise it: with an initializer and without. Arrays created with an initializer are called static arrays. They can be created wherever one can be created while arrays without initializers must be created within a loops or a method.

When you initialise an array with an initializer, you only have to write the values of the attributes, not the array. For example:

  • int[] numbers = {1, 2, 3};
  • int[] numbers2 = new int[3];

As you can see, if you use the initializer, numbers2 is initialized to 3, that’s because Java initializes the array by adding 0 to the number of elements you add. In this example, 3 + 0 = 3.

If you initialise an array, you have to create it within a loop or a method. Java automatically initializes each element of the array inside the method. For instance,