21 September 2020

How Arrays work in Java?

Welcome to another tutorial on the the "How to code in Java" tutorial series. In the last tutorial, we have gone through on how loops work in Java. In this tutorial, we'll be going through how arrays work in Java. I would recommend you to read on how loops work first as we'll be needing some knowledge on them. Now, let's get started with arrays.

So what is an array? You can think of it as a way to store a sequence of data with the same data type (all data types can be used). The data stored in an array are data that are related to each other in some ways. The data stored in it could be easily stored, accessed and searched. You can also think of an array as a way to declare multiple variables with the same data types. But don't store two unrelated data into the array, you might just confuse yourself when your program gets more prominent. Now, you might be asking, "why do we even need it?". Well, arrays are very useful when programmers need to deal with many data with the same data type. 

For example, imagine you need to calculate the average of 50 numbers. To calculate the average value you, of course, need to store them somewhere so that the numbers could be used by the system. But, would you declare 100 variable and as well as accessing the variable and perform calculation one by one? That methodology would work, but the process is really inefficient (if you have the patience for it that is). This where arrays help us to make the process even more efficient. By using an array, we just need to declare one (1) variable, and we're good to go. All we need to do afterwards is to store the numbers into the array, and we just need to use some syntax to access the data that we want later.

In most programming languages (including Java), we can declare and assign data into an array in one single line. But there's nothing wrong if you want to separate the initialisation and declaration of an array. There are many different types of arrays in programming, they're mostly categorised using dimension like 1-dimensional, 2-dimensional, 3-dimensional, etc. I'll walk you through until a 3-dimensional array as it's quite rare for people to use arrays with dimensions higher than 3(higher dimensions are more complicated). 


Index For the tutorial:



Single-dimensional Arrays.


A single dimensional array is an array that sequentially stores data, just like arranging things in a straight line. Like a variable in Java, to declare an array, you'll need a datatype and an identifier. While for initialisation, you'll need to create a new array with a specific type and size of the array. Then assign the reference of the array into the variable.

Declaring and initialising the arrays.


The initialisation of an array will create an array with the specified size, and the array will be filled with zeroes (0).

Initialised arrays by default are filled with zeroes (0).


The initialised array containing zeroes.


Here I imported the Arrays class from the "java.util" package so that I could print out the entire content of the array using the Arrays.toString() method. The method would give back us the whole contents in string form as you can see in the result. There's also a way for you to straight-up declare an array while assigning it with values. 

Declaring an array while assigning values into it in one line.

To access the numbers in the array, all we need to do is to use the index of the element. In an array, the index is the position of each element in the array. But unlike our regular indexes, the index in an array starts at zero (0). That means that to access the first element of an array, we'll need to use the index 0 to get the value. While to get the last element of an array, you need to access the element at the index, array_length - 1. To get the length or the size of the array, simply use the array's length properties (array_name.length). To access the following elements(items stored in an array) after the first one, you just need to use the next index number. The index number need to be closed by an open and close square bracket to access the element with the specific index.

The position of each elements in the array.

Accessing the 1st, 2nd, 4th and the last element of the array.


The 1st, 2nd, 4th and last element of the array.


Be careful to not and accidentally access an element that outside the size of the array. If you really did try to access an element with the index exceeded the size of the array, you'll get an ArrayIndexOutOfBoundsException. Where it'll cause the program to crash.

Accessing the 7th element of the array (which doesn't exist).


ArrayIndexOutOfBoundsException will only be triggered when you used an index exceeded the array size.


Enhanced for-loop.


In the last tutorial, I stated that we won't be covering the usage of enhanced for-loop because some array knowledge would be required. Since we've gone through a bit on about what an array is, let me show you how to print out every element in an array using a normal for-loop. Since index needs to start from 0, we'll need to initialise the control variable with the value 0, while using the length of the array as the condition (current index < array size). Then, we'll also need to add 1(one) in each loop iteration to the index, so that we could access the other elements.

A simple for-loop to iterate through the array.

Printing out all the elements of the array.

As we limited the loop to continue to run if the value of the control variable, the index is less than the length of the array. The loop will stop when the value reached 6 in the 7th loop iteration condition checking phase. Now you might be wondering, is there a better way to access the array's elements? There's indeed a way to iterate through the whole array without specifying the conditions, and we don't need to manage the value of the control variable ourself. By using the enhanced for-loop, we can iterate through the whole array with ease. The syntax for a enhanced for loop is as below:

for (data_type control_variable : array_name) {
    //any code that you want to use
}

Enhanced for loop to iterate through the array element and printing out their value.


Multi-dimensional Arrays.


Now comes the more tricky parts, the multi-dimensional array. A multi-dimensional array is just an array that contains an array in it and possibly another array inside that array. Each element in a multi-dimensional array contains an array. To declare a multi-dimensional array, you just need to specify during the declaration, how many dimension that your array will need. For example, to declare a 2D and a 3D array, you do something like this in Java.

2D and 3D array's declaration and initialisation.

Below is an example on a 2D and 3D array declaration and assigning value into the arrays. 2D arrays is simply an array of a 1D array while a 3D array is an array of 2D array. Well, that quite makes sense. 

Declaring and assigning values into the arrays.

To access the elements in a 2D array, we need to imagine the array's position as a grid, just like the arrangement I made in the code. In a grid system, the grid is positioned with the value x and y. Where x is the row's number of the cell and y is the column's number of the grid's cell. That works just fine for a grid system but remember, our array starts counting from zero (0). So you'll need to minus one for every horizontal and vertical coordinate that you want to access the array's elements.


Illustrating a 2D array, which looks like a grid.

For example, by using back the 2D array just now, to get the value that's the second row and second column. We need to use the statement, my2DArray[1][1] to access that element. We'll get 100 as the result when we access the element at that position.

Now, for a 3D array, things get quite complicated. To access the elements inside a 3D arrays, you'll need to first specify which row number that element is in for the first index. Then, the next index would be the index for the row number of the inner 2D array that you've accessed just now using the first index. After you have specified which row number to be used in the inner 2D array, the third index would be the column number of the element that we want to access. 

By using the previous 3D array that we declared, accessing my3DArray[1][1][1], it'll give us the value 150. Which is at the second row of the array, while in the second row of the inner 2D array and in the second column. I know that it's kinda hard to figure it out immediately, but try and see again how this works. If you still have no idea how this work, please leave a comment below and I'll help you as much as I can.

The 3D array structure.

Multi-dimensional arrays are used when you need to store more than one data for an entity in the array. For example, calculating the average score of the three subjects for the students of a class. Another example is to calculate expenses for the last 4 weeks where we categorise the data according to weeks, days and possibly time. 


Well, that's about all the things you need to know about arrays in Java. I hope you now know how to use an array and why to use it in programming. If you find this tutorial helpful, please share it with other people that might find it helpful. As always, if you have any question, suggestions, or questions, feel free to leave a comment in the comments section below. For the next tutorial, we will be looking into how type casting works in Java.

No comments:

Post a Comment