arrays
ArraysArrays allow multiple values of the same type to be stored together, instead of using individual variables for each value.
In Java, arrays are objects.
The individual values stored are referred to as elements of the array. The number of an individual element in an array is called an index. As with strings, indexes begin counting at 0.
int [] arr = {1, 2, 3}; // 1, 2, and 3 are elements of the array. The index of element “1” would be 0.
Arrays may be passed to or returned from methods. Once initialized, the length of an array cannot be changed.
Arrays must be declared and initialized before being used.
To declare an array of dimension n:
dataType [][]... arrName; // where there are n sets of square brackets
To initialize an array of dimension n:
arrName = new dataType [a1][a2]...[aN]; // where a1, a2, ... aN are the lengths of the 1 to N dimensions respectively
Initialization sets all values of an array to default (null, 0, false, etc).
To find the length of an array or its dimensions:
arrName.length // int value of the length of the nth dimension of an N-d array
arrName[a1].length // int value of the length of row a1 of an N-1 d array
To access a value from an array:
arrName[a1][a2]...[aN] // item at indexes (a1,a2,...aN)
int [] arr = {1, 2, 3};
arr[0] // value at index 0, hence 1
To change a value in an array:
int [] arr = {1, 2, 3};
arr[0] = 4; // changes the value of the element at index 0 from 1 to 4
Tips
If an index negative or greater than length - 1 is used, the ArrayIndexOutOfBoundsException will be thrown.
In Java, arrays may be “ragged”, which is to say that different rows may have different lengths.