Java Array
When you need to process multiple objects of the same type, you can save them in an array and then process them together as a single unit. It is a very convenient approach if you know how many objects the program will process during runtime.
You may consider an array as a collection of elements of the same type. All elements are stored in the memory sequentially.
All elements in a collection are stored under the same name. The possible number of elements to be stored is established when the array is created and cannot be changed. But a stored element can be modified at any time.
Arrays in Java
The picture below illustrates an array of five floating-point numbers. Each element has an integer index (0-4) to be accessed.
The first element has an index of 0, and the last element has an index equal to array size minus 1.
In Java, an array has the following important features:
- an array is a reference type;
- all array elements are stored in the memory sequentially;
- each element of the array is accessed by its numerical index, the first element has the index 0;
- the last element is accessed by the index equal to array size – 1;
- it is possible to create an array to store elements of any data type.
Declaration, instantiation, initialization
To create an array filled with elements we should:
- declare a variable of an array type (declaration);
- create an instance of the array object (instantiation);
- initialize the array by some values (initialization).
When we declare a variable, we define its type and name. Instantiation happens when memory is allocated for this object. Initializing the array object means that we put certain values of the array object into the memory of our program.
To declare an array, we must use two special characters [ ]
after the type of elements in the array:
int[] array; // declaration form 1
It can also be used after the name of the array variable:
int array[]; // declaration form 2: less used in practice
We will use the first form of declaration because it is most often used when writing Java.
Creating an array with specified elements
Java provides several ways to create an array with specified elements.
The simplest way to instantiate and initialize an array is to enumerate all its elements:
int[] numbers = { 1, 2, 3, 4 }; // instantiating and initializing an array of 1, 2, 3, 4
Another way is to initialize an array using variables:
int a = 1, b = 2, c = 3, d = 4;
int[] numbers = { a, b, c, d }; // instantiating and initializing an array of 1, 2, 3, 4
In this case, we should have all the elements at the moment of the array creation.
Creating an array using the "new" keyword
The most general way to create an array is to use the special keyword new
and specify the necessary number of elements:
int n = ...; // n is a length of an array
int[] numbers = new int[n];
This form is useful when the number of elements is known before starting the program. When we create an instance of the array object with indicated length like [n]
or [5]
and don't enumerate its elements explicitly, the array is initialized with default values of its type.
Now, the array has n
elements. Each element is equal to zero (the default value of the type int
). Next, we should make an explicit initialization of elements.
The size of an array cannot be greater than Integer.MAX_VALUE
. Actually, it is even slightly smaller than this value.
It's possible to separate declaration and instantiation into two lines:
int[] numbers; // declaration
numbers = new int[n]; // instantiation and initialization with default values
Also, we can write the keyword new
and enumerate all elements of an array:
float[] floatNumbers; // declaration
floatNumbers = new float[] { 1.02f, 0.03f, 4f }; // instantiation and initialization
By default, an array of a primitive type is initialized with default values. For other values, you need to fill values explicitly or use the utility class Arrays
. It provides a convenient way to fill a whole array or a part of it with some values:
int size = 10;
char[] characters = new char[size];
// It takes an array, start index, end index (exclusive) and the value for filling the array
Arrays.fill(characters, 0, size / 2, 'A');
Arrays.fill(characters, size / 2, size, 'B');
System.out.println(Arrays.toString(characters)); // it prints [A, A, A, A, A, B, B, B, B, B]
The length of an array
To obtain the length of an existing array, access the special property arrayName.length
. Here is an example:
int[] array = { 1, 2, 3, 4 }; // an array of numbers
int length = array.length; // number of elements of the array
System.out.println(length); // 4
Accessing elements
The values of elements of an array can be changed. You can use the index to set a value of the array or to get a value from it.
Set the value by the index:
array[index] = val;
Get the value by the index:
val = array[index];
Indexes of an array have numbers from 0 to length – 1 inclusive.
Let's look at an example.
int[] numbers = new int[3]; // numbers: [0, 0, 0]
numbers[0] = 1; // numbers: [1, 0, 0]
numbers[1] = 2; // numbers: [1, 2, 0]
numbers[2] = numbers[0] + numbers[1]; // numbers: [1, 2, 3]
This code works as follows:
- In the first line, the array of integers named
numbers
with three elements in it is created. It is initialized with default values, which is 0 for theint
type. - In the second line, the value "1" is assigned to the very first element of the array by its index (do not forget, the first element has the index 0).
- In the third line, the value "2" is assigned to the second element of the array by its index (numbers[1] is the second element).
- In the last line, the sum of the first two elements is assigned to the third element by its index.
If we try to access a non-existing element by an index then a runtime exception occurs.
For instance, let's try to get the fourth element (with index 3) of the considered array numbers
.
int elem = numbers[3];
The program throws an ArrayIndexOutOfBoundsException.
Processing Arrays Using Loops
It's quite useful to process an array by going through it with a loop. The length
property of an array can help you avoid an ArrayIndexOutOfBoundsException
.
You can fill an array with the square of its element's index. The example below shows how:
int n = 10; // the size of an array
int[] squares = new int[n]; // creating an array with the specified size
System.out.println(Arrays.toString(squares)); // [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
/* iterating over the array */
for (int i = 0; i < squares.length; i++) {
squares[i] = i * i; // set the value by the element index
}
System.out.println(Arrays.toString(squares)); // [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
The code above creates a ten-element array, initially all zeros. Then it sets each element's value to the square of its index. It turns the array into a string, displaying all elements inside square brackets and print this string on the screen.
Next, let's see how to use a loop to check an array's elements order.
The program below verifies if the provided array is sorted in ascending order. It prints OK
if it is, and BROKEN
if not.
int[] numbers = { 1, 2, 3, 4, 5, 10, 6 }; // the order is broken
boolean broken = false; // suppose the array is well-ordered
/* iterating over the array */
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] < numbers[i - 1]) { // if the order is broken
broken = true; // write a result
break; // terminate the loop
}
}
if (broken) {
System.out.println("BROKEN");
} else {
System.out.println("OK");
}
In this program, for the provided array, the output is BROKEN
.
You can also use while and do-while loops for array iterations, but these aren't typically used as often.
An array of arrays
Array is a structure allows you to store elements of the same type. But why limit yourself to just one dimension? It would be so convenient to store matrices, 3D objects, or even 4D objects in one array! And now is the time: the adventure into multidimensional arrays is starting in three...two...one!
First, let's figure out what we mean by a multidimensional array and why it is different from a single-dimensional array.
We can say that a multidimensional array is an array of arrays. That is, to create a multidimensional array, we need to think of an array as an element of another array. Eventually, we get a multidimensional array.
A multidimensional array makes it very easy to represent things that have more than one dimension: for example, 3D objects with length, height, and width. The universe we live in could be described with four dimensions, time being the fourth dimension, so it is 4D. Higher levels like 5D and so forth are hard to imagine at first, but when you put it into practice using multidimensional arrays, you'll see that it is indeed possible.
For now, let's look at some more down-to-earth examples. A seat in the theater can be indicated with a 2D-array: one index for the row, and another for the number of the seat in that row. If you want to write a game that uses maps such as Sea Battle, two-dimensional arrays will be very helpful in setting coordinates on the map. Besides, some mathematical structures are conveniently represented as multidimensional arrays.
Let's take a look at a case of a multidimensional array that is used quite often in practice: a two-dimensional array.
2-dimensional arrays
If a one-dimensional array can be represented as a single sequence of elements, then an intuitive way of representing a two-dimensional array is a matrix or a table. If you're working with matrices or tables in your program, it makes sense to present them in the form of two-dimensional arrays.
Let's create a two-dimensional integer array with 3 rows and 3 columns. Here is what it looks like:
int[][] twoDimArray = {
{0, 0, 0}, // first array of ints
{0, 0, 0}, // second array of ints
{0, 0, 0} // third array of ints
};
You can picture it as a table:
We can say that the arrays with three zero elements are nested in the twoDimArray
. The main array that contains other arrays is called the main array.
Here's an interesting feature: nested arrays do not necessarily have to be of the same size. In the example below, each new embedded array has different lengths:
int[][] twoDimArray = {
{0, 0}, // the length is 2
{1, 2, 3, 4}, // the length is 4
{3, 3, 3} // the length is 3
};
You can create nested arrays with different numbers of elements in the same 2D array.
Access the elements
Let's see how we can access an element of an array. The idea is the same as for one-dimensional arrays, but now we have to write two indices: first the index of the element of the main array, and then the index of the nested array.
Suppose we need to access an element that is in the first row and the first column. How do we find this particular element? As you recall, a 2D array is an array of arrays. So, start by selecting one of the nested arrays by its index in the main array. The principle is similar to a 1D array.
int[][] twoDimArray = {
{3, 4, 5}, // [0]
{6, 7, 8}, // [1]
};
First, go to the main array and choose the nested array with its index:
Second, in this nested array, choose the required element with its index. This is also like in simple arrays:
Let's create a new variable int number
and put in it the element of the first row and the first column of our array:
int number = twoDimArray[0][0]; // it is 3
Remember that in all arrays, indexing starts with 0!
The following code will show all the elements of the two-dimensional array twoDimArray
:
System.out.println(twoDimArray[0][0]); // 3
System.out.println(twoDimArray[0][1]); // 4
System.out.println(twoDimArray[0][2]); // 5
System.out.println(twoDimArray[1][0]); // 6
System.out.println(twoDimArray[1][1]); // 7
System.out.println(twoDimArray[1][2]); // 8
Working with 2D arrays
In the previous examples, we were creating 2D arrays by enumerating all the elements. But one of the most popular ways to create a multidimensional array is using the for
loop.
Let's create twoDimArray
with 2 rows and 10 columns and fill it with ones. To get access to every element we need to iterate through two for
loops. The first for
loop chooses the nested array and the second for
loop iterates over all the elements of the nested array.
int[][] twoDimArray = new int[2][10];
for (int i = 0; i < twoDimArray.length; i++) {
for (int j = 0; j < twoDimArray[i].length; j++) {
twoDimArray[i][j] = 1;
}
}
You can print all nested arrays:
for (int i = 0; i < twoDimArray.length; i++) {
System.out.println(Arrays.toString(twoDimArray[i]));
}
The output will be:
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
And to print every element we also need two for
loops. In the example below, we increase all the elements by one and print them to the standard output:
for (int i = 0; i < twoDimArray.length; i++) {
for (int j = 0; j < twoDimArray[i].length; j++) {
twoDimArray[i][j]++;
System.out.print(twoDimArray[i][j] + " ");
}
System.out.println();
}
So, the output will be:
2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2
Multidimensional arrays (>2)
We are finally ready to deal with more complex concepts. There are types of arrays with more than two dimensions. Even though it is more difficult to understand what they look like, don't worry: you will get used to working with them.
First of all, a three-dimensional array can be represented as a cube or a box: it has exactly three dimensions — length, width, and height. Take a look at this three-dimensional array with 24 elements:
The following practical situation also can help you to understand three-dimensional arrays: Imagine that you need to figure out where the car is in a multi-story parking lot. Then you have to set three numbers, or three coordinates: floor, row, and place in a row.
Last, but not least: you can imagine a three-dimensional array like this:
In each element of a two-dimensional array, you have another nested array.
The code below creates the three-dimensional array you just saw above:
int[][][] threeDimArray = new int[2][3][4];
int element = 0;
for (int i = 0; i < threeDimArray.length; i++) {
for (int j = 0; j < threeDimArray[i].length; j++) {
for (int k = 0; k < threeDimArray[i][j].length; k++) {
threeDimArray[i][j][k] = element;
}
element++;
}
}
Here 2
is the number of rows, 3
is the number of columns and 4
is the number of elements in a nested array.
And let's print the nested arrays:
for (int i = 0; i < threeDimArray.length; i++) {
for (int j = 0; j < threeDimArray[i].length; j++) {
System.out.print(Arrays.toString(threeDimArray[i][j]) + " ");
}
System.out.println();
}
The output will be:
[0, 0, 0, 0] [1, 1, 1, 1] [2, 2, 2, 2]
[3, 3, 3, 3] [4, 4, 4, 4] [5, 5, 5, 5]
Accordingly, in order to refer to an element of the three-dimensional array, we need three indices:
System.out.println(threeDimArray[0][0][0]); // 0
System.out.println(threeDimArray[0][1][0]); // 1
System.out.println(threeDimArray[1][0][1]); // 3
System.out.println(threeDimArray[1][2][3]); // 5 – the last element of the last array
Notice, that you can simplify your code by using for-each loop and methods of the class Arrays
to fill and print multidimensional arrays.
And, of course, you can create arrays of other dimensions by analogy — 4, 5, 6, and so on. Just remember that an element of a multidimensional array has as many indices as dimensions of that array.