Arrays are a fundamental data structure in programming, representing a numbered collection of variables of the same type. In this tutorial, you will learn how to declare arrays in Java and explore different ways to initialize and work with them.
Creating an Array
To begin with, let’s look at how to create an array in Java, the syntax for declaring an array is as follows:
dataType[] arr;
Where:
- dataType – represents the type of data that the array will contain (such as int, String, etc.). It can be a primitive data type or java object.
- [] – indicates that we are creating an array.
- arr – the name of the array.
Additionally, we can specify the size of the array using the following syntax:
int[] intArray = new int[5];
This creates an array of integers with a size of 5, allowing you to store up to 5 elements. It’s important to note that the size of an array is fixed and cannot be changed after it is created.
Initializing an Array
Once we have declared an array, we can then proceed to initialize it. There are several ways to do this in Java:
1. Initialize an Empty Array
One method is to initialize an empty array, as seen in the first line. However, attempting to add an element to this array will result in an IndexOutOfBoundsException. Another way to initialize an empty array is shown in the second line.
int[] arr = new int[]{}; int[] arr1 = {};
2. Initialize Array with Values
In the following two lines of code, initialize two different arrays.
int[] arr2 = {1,2,3}; int[] arr3 = new int[]{1,2,3};
The first line of code creates an array called “arr2” and initializes it with the values 1, 2, and 3.
The second line of code creates an array called “arr3” using the “new” operator and then initializes it with the values 1, 2, and 3. It’s equivalent to:
int[] arr3 = new int[3]; arr3[0]=1; arr3[1]=2; arr3[2]=3;
Both lines of code create an array of integers with the same values, but the second line uses a slightly different syntax to accomplish the same thing.
It’s important to note that if we try to add an element that is not the same type as others, we’ll get a compiler error.
3. Declare Array Size and Then Initialize
Another way of creating an array is to declare it with a size and then initialize (add) elements 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, and the third (last) element has an index of 2.
Printing array elements
To learn how to print array elements, check out our tutorial on Printing Array Elements.
Multidimensional Arrays
Finally, for those who want to explore multidimensional arrays, check out our tutorial on Multidimensional Arrays in Java.
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!