An array is a commonly used and fundamental data structure in Java. The array allows us to store a number of values of the same type in computer memory.
In this short tutorial we’ll introduce arrays in Java.
Arrays are a useful data structure when we need to work with a number of values of the same type. For example, lets say we need to write a function that sums an unknown number of integers. How, can we represent this collection of elements in such a way that we can process them generically.
Well, we need a data structure that can hold a number of values and treat them as a single variable. One such solution is to use a Java array.
A Java array is a reference type, and as you probably know, a variable of a reference type holds the memory location of its value in memory. However, instead of pointing to a single value in memory, an array can hold N number of values known as elements of the same type. These elements are held in memory at continuous memory locations.
The above image shows how an array would represent the integers 1 to 6 in computer memory. As we can see an array to hold 6 integers (elements) allocates space in memory to store the 6 integers. The integers are held at continues memory locations. The variable numbers points to the memory address of the first element of the array. Therefore, an array knows at what memory address each value is stored. This makes it extremely fast to retrieve an element from an array using its index called a subscript.
Now, lets look at how to declare the numbers array in Java.
The general syntax for declaring an array is:
1 | <DATATYPE>[] <VARIABLE_NAME>
|
Therefore we can declare our number array as follows:
1 | int[] numbers;
|
Just like any other local variable we must initialize an array before use, otherwise we will receive a compile time error. Moreover, above we have declared a variable that holds an array of type integers.
However, to do anything useful with an array we need to define the number of elements, so the correct amount of memory can be allocated.
1 | int[] numbers = new int[6];
|
Above we declare the array to have 6 elements. However, we haven’t explicitly filled the array with integers, instead each index / element in the array of 6 integers is filled with the default value of the data type, and in this case it is the value 0.
We can access the elements of an array using its index. The first element of the array is accessible from index 0 and the last element is accessible from the index:
1 | lastIndex = Array Length - 1
|
Let’s look at an example of accessing the elements of the numbers array using its index also known as a subscript. If you remember our numbers array has 6 elements.
1 2 3 4 5 6 | int firstElement = numbers[0];
int secondElement = numbers[1];
int thirdElement = numbers[2];
int fourthElement = numbers[3];
int fifthElement = numbers[4];
int sixthElement = numbers[5];
|
We can also get the length of an array using it’s length property.
1 2 3 4 5 | @Test
public void arrayLength() {
int[] numbers = new int[6];
assertEquals(6, numbers.length);
}
|
The length property returns the number of elements that an array can store. Therefore, we can also use the length property to access the last element of an array.
1 | int lastNumber = numbers[numbers.length -1];
|
Moreover, the first index to the last index of an array is known as the bounds of an array. If we try to use an index that is outside of the bounds of the array, an ArrayIndexOutOfBoundsException will be thrown. To learn more about Exceptions in Java see this tutorial.
1 2 3 4 5 | @Test(expected = ArrayIndexOutOfBoundsException.class)
public void outOfBounds() {
int[] numbers = new int[6];
int outsideOfBounds = numbers[10];
}
|
Let’s now look at how to initialize an array with values other than the defaults.
The first approach is to explicitly set the values when we declare the array.
1 2 3 4 5 6 7 8 9 10 | @Test
public void initializeViaDeclaration() {
int[] numbers = new int[] {1,2,3,4,5,6};
assertEquals(1, numbers[0]);
assertEquals(2, numbers[1]);
assertEquals(3, numbers[2]);
assertEquals(4, numbers[3]);
assertEquals(5, numbers[4]);
assertEquals(6, numbers[5]);
}
|
Above we declare the array with its values – the integers from 1 to 6. When we declare an array in this way the number of values sets the length of the array. Therefore, we don’t explicitly set the length of the array as we did before.
1 | int[] numbers = new int[6];
|
We can also initialize an array using a for loop.
We normally work with arrays using Java For Loops.
We can use a for loop to process an array. In particular, we can iterate through an array, retrieving, or writing it’s elements using an index.
1 2 3 4 5 | int[] numbers = new int[]{1, 2, 3, 4, 5, 6};
for (int index = 0; index < numbers.length; index++) {
System.out.println(numbers[index]);
}
|
In the above for loop, we iterate through the array bounds, and print its elements to the console. If you remember the array bounds start from the first element at index 0, to the last element which is the length of the array – 1.
We can also use this approach to initialize an array.
1 2 3 4 5 6 7 | final int arrayLength = 6;
int[] numbers = new int[arrayLength];
//initialize array
for (int index =0,value=1; index < arrayLength; index++, value++) {
numbers[index] = value;
}
|
Above, we initialize the numbers array with the integers from 1 to 6.
We can also use an Enhanced For Loop to iterate an array.
1 2 3 4 5 | int[] numbers = new int[]{1, 2, 3, 4, 5, 6};
for (int number : numbers) {
System.out.println(number);
}
|
Above we use the enhanced for loop to iterate the numbers array. The enhanced for loop provides a more concise syntax compared to the traditional for loop.
Now that we understand the basics of working with arrays. Let’s implement the scenario we discussed at the start of the tutorial to sum an array of integers.
1 2 3 4 5 6 7 8 9 10 11 12 | public static int sum(int[] arrToSum) {
if (arrToSum == null || arrToSum.length == 0) {
return 0;
}
int sum = 0;
for (int value : arrToSum) {
sum += value;
}
return sum;
}
|
Above we create a method sum that takes an integer array as a parameter. We use an enhanced for loop to iterate the array and sum its elements.
1 2 3 4 5 6 | @Test
public void sum() {
final int[] arrToSum = new int[]{1, 2, 3, 4, 5, 6};
final int expectedSum = 21;
assertEquals(expectedSum, ArrayExample.sum(arrToSum));
}
|
In this short tutorial we looked at the basics of working with arrays in Java.