What is an array?
An array allows us to store multiple values of the same data type in a single variable.
This is really helpful when we have lots of variables that are all related.
You can create an array of any type or object by writing the type and [].
We can declare an array of integers like this:
int[] grades;
We can now add values to it, like so:
int[] grades = {100,92,97,96,85};
In fact, we can create many different types of arrays:
String[] names = {"Greg","Rodrick","Frank","Susan","Manny"};
boolean[] switches = {true,false,true,true,false};
double[] monthlyTemps = {99.5,70.6,87.9,60.4};
Accessing values in an array
Remember when we talked about indexes and ordering in the String Manipulation lesson? Well, that's exactly how arrays work.
When you count, you normally count like this: 1,2,3,4,5.... It makes sense, right?
But in Java (and many other programming languages), we count like this: 0,1,2,3,4...
0 is the first item. 1 is the second item. 2 is the third item. And so on and so on.
We can use this to access individual values in an array, using [].
int[] grades = {100,92,97,96,85};
System.out.println(ghrgrades[0]); // prints 100
System.out.println(grades[1]); // prints 92
System.out.println(grades[4]); // prints 85
Using For Loops
We can also use for loops (and while loops, but we know how many values exist) to iterate through the array.
We can use length (NOT length()) to get the number of items in the array, and iterate through.
int[] grades = {100,92,97,96,85};
for(int i = 0; i < grades.length; i++) {
System.out.println(grades[i]);
}
This will display each value in grades on its own line.
Setting array values
We can treat individual array items like variables, so we change the values like variables;
int[] grades = {100,92,97,96,85};
grades[0] = 90;
grades[grades.length-1] += 5; // adds 5 to the last item in the array