How to Declare an Array in Java?

An array is a data structure representing a numbered collection of variables of the same type. Let’s see how to declare an array in Java. 

To learn how to work with a multi-dimensional array, check the Multidimensional Arrays in Java tutorial. 

How to declare an array in Java?

We declare arrays in the following way:

dataType[] arr;

Here:

  • dataTypethe type of data that the array will contain. It can be a primitive data type or java object.
  • [] – indicates that we want to create an array
  • arr – the name of the array

We can also specify how many elements they should array contain (the size of an array):

int[] intArray = new int[5];


Here, we declare an array with the size of 5. So, we can add up to 5 elements.

We can also declare and initialize an array at the same time:

int[] arr = new int[]{};
int[] arr1 = {};
int[] arr2 = {1,2,3};
int[] arr3 = new int[]{1,2,3};


These are all valid ways to declare and initialize an array in Java.

In the first line, we initialized an empty array. If we try to add an element, we’ll get IndexOutOfBoundsException. We used another way to initialize an empty array on the second line.

On the third line, we declared and initialized an array with values 1,2,3. The array size is three, and we can not add more elements to it.

On the 4. line, we used another way to initialize the array’s values.

If we try to add an element that is not the same type as others, we’ll get a compiler error.

Another way of creating an array is to declare with a size and then initialize (add) an element afterward:

String[] arr = new String[3];

arr[0] = "value 1";
arr[1] = "value 2";
arr[2] = "value 3";

Indexing of elements in an array starts at 0. So we add the first element on position 0. The third (last) element has an index of 2.

Look at the Print Array Elements tutorial to learn how to print array elements. 

That’s all about how to declare an array in Java. To learn more about Arrays, please check the Java Arrays tutorials page. 

Happy coding!

Leave a Reply

Your email address will not be published.