Arrays

Variables are used to hold a single value. For example:

int age = 12;
String name = “Sarah”;

However, what if a program needed a list of names? We don't want to declare multiple variables with meaningless names like name1, name2, name3, etc.

Arrays allow us to store multiple values of the same type. Just put brackets [] after the type and before the name.
E.g.

String[] names = {"Sarah", "Joe","Ali", "Jose"};
int[] ages = {12, 15, 9, 5};

If we don't know the values, but we know that we are going to have 4 of them in our array, we can declare the array as follows:

String[] moreNames = new String[4];
int[] moreAges = new int[4];

Unfortunately, we need to know exactly how many elements we are going to get before we can initialize the array because its length cannot change once it is set.

We access the elements of an array by using an index in brackets []. The indexes start at 0.
NOTE: The highest posssible index is the length of the array - 1.

In the case of the names array above, we could use the index to print each name as follows:

System.out.println(names[0]);
System.out.println(names[1]);
System.out.println(names[2]);
System.out.println(names[3]);

..but imagine how many lines of code you would need for 100 names...

So, in order to process each element in an array, we should use a for loop, and use the length of the array to supply the end point, like this:

for (int i=0;i<names.length;i++) {
     System.out.println(name[i]);
}

Another type of for loop is available for processing all the elements of an array.
It is called a "for each" loop and the syntax looks like this:

for (String name : names) {
     System.out.println(name);
}
for (int age : ages) {
     System.out.println(age);
}

Each time the loop repeats, the variable (name or age) gets a new value from the next element of the array.
The loop will repeat until there are no more elements in the array.