i

JAVA Complete Course

Arrays

Java arrays are containers which helps us to save multiple values in a single variable, instead of declaring then in each one. Array can be container of any type which we mentioned earlier. To declare concrete type of array we are using square brackets.

With the statement above we declared array of Strings which has variable name cars. To insert values to it, we can use an array literal - place the values in a comma-separated list, inside curly braces:

Array is an index based container, which means that in order to access array we can use index. Indexes are 0 based in java, so the first element of array has index 0, second has 1, and so on. For example, to access first element of cars array, we should write the following command:

Also, we can change the actual value of any element in array by setting it on concrete index.

Sometimes we need to know how many elements are in our array. For this we should use length property of it:

Sometimes we need to loop throughout the whole array. For this we need to use one of Java loop operators: for or while. Java also supports for-each loop

The template of using for-each loop is below

Above we were speaking a lot about one dimensional arrays, but in Java we can have multidimensional arrays as well, in other words: array of arrays. A multidimensional array is an array containing one or more arrays. To create a two-dimensional array, add each array within its own set of curly braces:

myNumbers is now an array with two arrays as its elements. To access the elements of the myNumbers array, specify two indexes: one for the array, and one for the element inside that array. Example below accesses the third element (2) in the second array (1) of myNumbers:

We will visit looping arrays in future, but just for interest let’s see how can we iterate through the all elements in multidimensional arrays.