Programs frequently need to deal with many instances of something: for example consider a program that how many people attended each robotics meeting. You could create a variable for each robotics meeting:

  int meeting1_attendees;
  int meeting2_attendees;
  int meeting3_attendees;
  int meeting4_attendees;

But that's awkward (especially if you met 50 times during the season). Fortunately, Java offers a type of variable called an array.

The following declares a variable that stores 50 integers:

   int meeting_attendees[]=new int[50];

To print the attendees at meeting 3 you would use:

   System.out.println("Meeting 3 attendees:"+meeting_attendees[2]);

Notice that the 3rd element of the array is at index 2 since the first element is at index 0.

Arrays are particularly powerful when you combine them with loops; consider the following:

   for (int mtg=0; mtg<50; mtg++) {
       System.out.println("Meeting "+mtg+" attendees:"+meeting_attendees[mtg]);

Loops and arrays give you a concise way to programmatically process large collections of data.

Extra credit

Last modified 2 years ago Last modified on Aug 3, 2020, 5:31:23 PM