I am currently in the process of learning the Java programming language, and I need help understand the size method of the ArrayList class. Before asking the question, let me explain the program.
This program finds the average of class grades.
My question would be about the size method of the ArrayList class. In the For-Loop, the relational expression, "i < grades.size()", will run "i" until it is less than the size of the array. I was instructed that the size of the array is always one more than the number of elements in the array, so in my case, given that I have 3 elements (grades) in my array, I actually have an array size of 4 (similar to how a string works). Notice that after I am out of the For-Loop, I am able to appropriately calculate my average with the size method. I am confused because if the size of the array would be one more than the number of elements, then would it not just divide by 4 rather than 3? Why do the rules function differently in a For-Loop? Thank you for anybody willing to shed light on this.
import java.util.ArrayList;
public class Chap11Part1
public static void main(String[] args)
{
double average;
int total = 0;
ArrayList<Integer> grades = new ArrayList<Integer>();
grades.add(78);
grades.add(84);
grades.add(90);
for(int i = 0; i < grades.size(); ++i)
total += grades.get(i);
average = total / grades.size();
System.out.println("The average is " + average);