Now it's time to introduce another data type, Arrays! Arrays are simply a collection of elements of a certain type. They make it much easier for us to store information as we can store multiple values in one variable.
To create a new array there are a few things we need to do.
First, determine the type of the array (what objects/data-types will it hold).
Second, determine the size of the array (how many objects we will allocate space for).
Lastly, decide on an appropriate name that we will use to reference it (variable name).
Once we know this we can create an array using one of two different methods.
1. We can create an empty array with a predefined size. We will add the values after.
2. We can create an array by defining the values that it will hold.
Types of Arrays
It is important to understand that arrays can only hold one type. And that type must be the one that was declared when initially creating the array. For example, we cannot have an array that contains both Strings and Ints.
Size of an Array
The size of an array is a constant value and one declared cannot be changed. This is important as we may want to add additional items to an array which is not possible. To do something like this we would have to create a new array with an increased size. Then copy the contents of the first array into the new array along with the additional values.
Since our arrays contain multiple values we need a way to access each individual element. In Java we can do something called Indexing. When we create an array an integer from the range 0 -> (size of array -1) is automatically associated with each element in our array. We can use these integers to access our elements. The integer 0 will represent the first element in the array while the (size of array -1) will represent the last element. For example if we have an array of size 4 then 0 will be the first element and 3 will be the last.
We use these integers in the following way to access unique elements.
Now that we know how to access specific elements we actually know how to change them as well. We can simply assign an index (newArry) = to something.
Getting the Size of an Array
Sometimes we are unsure about how large our array is. To get the size/length of the array we can use the .length property of arrays.