Arrays are a primary way to store linear, ordered collections of data. The elements of an array must all have the same type. An array type is written by appending [] to the type of the array elements. For example, the type of an array of int values is written as int[], whereas the type of an array of String values is written String[]. We create an array with the new keyword, like so:
int[] arr = new int[50];
The above code makes space in memory (called allocating) for a sequence of 50 int values, and stores the location of that space in memory in the newly-created variable arr.
By default, all ints in our array will be set to zero. If we wish to initialise our array with other values, we can include them in the new invocation like so:
// size no longer needed as javac will count the elements
int[] arr = new int[]{10,100,-2,8,0};
We can access the contents of an array by index. The ith element of the array a (starting counting at zero) can be retreived using the notation a[i], for example:
int first = arr[0];
IO.println(first + " is the first (index 0) element!");
We can also update elements of an array using this notation:
arr[0] = first + 1;
IO.println("The first element is now: " + arr[0]); // prints 11
To get the length of an array a, we can write a.length:
int len = arr.length;
IO.println("The array arr has " + len + " elements.");