Skip to content

Arrays

A Java array is a special type of object variable that serves as a container to hold structured data of one type. We can refer to its individual elements with index.

For example, if we wanted to store 1000 names in our application, we wouldn't have to declare 1000 variables of the String type, but only declare one 1000-element array variable that stores strings of the String type.

To declare an array, you need to specify the type of data stored in the array and specify its size. The size of the array should be constant, so when declaring an array, the size must be specified or the elements must be explicitly declared so that the compiler can calculate the length of the array itself.

There are two basic types of arrays:

  • one-dimensional
  • multidimensional

We will discuss the differences between them below.

One-dimensional arrays

The schema of the array type declaration is as follows:

type[] table name = new type[number of elements];

How should we read this declaration? We have created an array variable (or more precisely a one-dimensional array) named table_name and sizenumber of elements, which will store elements oftype`. Below is an example:

String[] myArray = new String[10];

In the example above, we have declared a 10-element array that will hold elements of the String type.

It is also possible to declare an array without specifying its size, but the individual elements of the array should be openly initiated inside the curly brackets separating the individual elements with a comma sign, e.g., "String:

String[] array = new String[] {"Hello", "World", "!" };

Here are some examples of table declarations of different types:

int[] myNumbers = new int[5];
int[] myNumbers2 = new int[]{1, 2, 3};
String[] myStrings = new String[2];
long[] myLongs = new long[3];

Table initialization and default values

When declaring an array and not specifying what data to be completed, it will be completed with default values for the selected type, e.g. for numbers it will be 0, and for reference variables: null. This is well illustrated by the example:

String[] forenames = new String[4]; // we have declared an empty 4-element array storing character strings

array default values

The indexes of tables

Values stored in arrays can be written and read using the indexes under which they are located. Indices are natural numbers. Index numbers begin with 0, i.e., the first element will be located in the array under index number 0. The last element will be located under an index with a value of size_table -1. Remember not to exceed the array index numbering range, because the compiler will report an exception java.lang.ArrayIndexOutOfBoundsException.

Let's use the initialized array name from the previous example and modify the corresponding fields:

String[] names = new String[4];
names[0] = "John";
forenames[3] = "romance";

System.out.println("Element number 1: " + forenames[0]); // Element number 1: Jan
System.out.println("Item number 2: " + names[1]); // Item number 2: null
System.out.println("Item number 3: " + names[2]); // Item number 3: null
System.out.println("Element number 4: " + names[3]); // Element number 4: rom

Graphical status of the array after the operations of modification of its relevant cells is now as follows:

array indexes

Going over the array

To print all values of the array name from the previous example, we called the printing method System.out.println() four times, each time changing the cell index. We can say that this is not quite a "nice" and automatic method. We are helped by the for loop instruction already known to us. How do we use this method for arrays? Quite easy: just go through all the array elements in the for loop (make the so-called iteration) using the control variable that will refer to the corresponding array index. An example is shown below:

int tabLength = 4;
String[] names = new String[tabLength];
forenames[0] = "John";
forenames[3] = "roman";

for (int i = 0; i < tabLength; i++) {
    System.out.println("Element number " + (and + 1) + ": " + names[i]);
}

The effect is identical to the previous example, and the code is more universal and automated - we do not repeat each item's print call code separately - this is provided by the for loop. It should also be noted that, as previously written, we iterate from an index numbered 0 to an index tabLength - 1, where tabLength is the size of an array.

Downloading an array size

It is possible to download the array length. The length attribute can be used for this, as the array is an object type and therefore has built-in methods and attributes. Here is an example:

``java String[] myArray = new String[10]; System.out.println(myArray.length); // 10

## Multidimensional arrays

As we mentioned earlier, arrays can also store any object, not just simple types. There is therefore nothing to prevent an array from storing other arrays as well, as the array is also an object. Therefore, you can create two-, three- or multidimensional arrays. A two-dimensional array is nothing more than a structure containing rows and columns that store data.

The basic declaration and initialization of a two-dimensional array looks like this:

```java
type [][][] name of the table; // table declaration
table name = new type[number of rows][number of columns]; // table initialization
type[][][] table name = new type[number of rows][number of columns]; // declaration and initialisation in one

The number of columns and rows need not be identical, so you can create any rectangular arrays. An example of creating and initializing an array that stores character strings:

String[][] myArray = new String[2][];
myArray[0] = new String[]{"Alice", "has", "cat"}; // create the first line, i.e. with index number 0
myArray[1] = new String[]{"Cat", "has", "Alice"}; // create a second line, i.e. with index number 1

As you can see in the example above, you can initialize the rows of a two-dimensional array with one-dimensional tables. And how to refer to individual elements of a two-dimensional array? We present this below using a previously created array called myArray:

System.out.println(myArray[0][0]); // Alice
System.out.println(myArray[0][2]); // cat
System.out.println(myArray[1][1]); // has
System.out.println(myArray[1][3]); // Error! The java.lang.ArrayIndexOutOfBoundsException will be thrown

As you can clearly see in the example, the first coordinate represents a row of the array, the second - a column, the standard numbering starts with index number 0. Remember not to exceed the range of declared array sizes!

Going through all the elements of a two-dimensional array is analogous to iterating after a one-dimensional one. The only difference is that we additionally add a second nested for loop: the first loop will iterate after rows, while the second loop will iterate after columns. Here is an example:

for (int i = 0; i < myArray.length; i++) {
    for (int j = 0; j < myArray[i].length; j++) {
        System.out.print(myArray[i][j] + " ");
    }
    System.out.println();
}

Let's clarify a few things:

  • The expression myArray.length will return the number of lines of the table
  • The expression myArray[i].length will return the number of columns in a row
  • The table cell is referenced by myArray[i][j], where i and j are the current row and column indices.