Arrays – what, when, and why?
So far, we’ve only seen single values, such as int
, double
, and String
. Imagine we want to calculate an average result. That would look something like this:
double result1 = 7.0;double result2 = 8.6; double result3 = 9.0; double total = result1 + result2 + result3; double average = total / 3; System.out.println(average);
This code isn’t very scalable. If we were to add a fourth result, we would need to do three things in order to make this work:
- Declare and initialize a fourth variable
- Add this fourth variable to the total
- Divide by
4
instead of3
This is a hassle, and it is error-prone. If we knew arrays, we could alter this by only changing one element of our code. Let’s see what arrays are. Then, we will rewrite this example once we get to iterate over arrays.
Java can’t do basic math?!
If you were to run the previous code snippet, you’d see something interesting. If I asked...