Java arrays
Arrays are a very important concept in Java as well as many other programming languages. An array is a special type of variable which can store a list of values.
This tutorial focuses on:
- The necessity of arrays
- Declaring arrays
- Adding values to an array
- Accessing an arrays elements
- Modifying an arrays elements
- Getting the length of an array
The necessity of arrays
Imagine you are writing a program that has three variables which store vowels. Your code for these three variables would probably look like this:
With Arrays, it is much simpler. An array gives you the ability to group together related variables into one set. Arrays are special variables which can store a list of values. Therefore, instead of the code above you can declare a 'vowels' array:
Declaring arrays
Arrays are declared with a data type, an array name, and square brackets [] specifying that you are declaring an array.
After an array is declared, an array object has to be assigned to it using the new keyword as well as the length of the array - specified in the square brackets. The length of the array denotes how many elements an array can hold.
The above example declares an array named evenNumbers of data type int which has a length of 10, therefore it can store 10 elements.
Adding values to an array
Add values to an array by referring to the appropriate index of the array and assigning it a value.
The above example will assign the value 20 to the 4th element in the evenNumbers array.
NOTE: Array indexes begin at 0, so the first element of an array is at index 0, the second element of an array is at index 1, and so on.
As an alternative to declaring an array and then assigning values to its elements, you can do both tasks together.
The above example declares an array named vowels of data type char which stores six elements.
Accessing an arrays elements
You can access an arrays elements by referring to the array by its name and the appropriate index number of the element you wish to access.
Modifying an arrays elements
You can modify an arrays elements by referring to the array by its name and the appropriate index number of the element you wish to modify.
Getting the length of an array
The length of an array is the number of elements in it. To get the length of an array, use the length property of the Array object with the array whose length you want to find out.