Free Ebook cover Java for Beginners: A Complete Introduction to Programming with Java

Java for Beginners: A Complete Introduction to Programming with Java

New course

10 pages

Arrays and Basic Collections for Handling Multiple Values

CapĂ­tulo 8

Estimated reading time: 7 minutes

+ Exercise

Why Arrays and Collections Matter

Many programs need to work with multiple values of the same type: a list of test scores, daily temperatures, names of students, or prices in a cart. Instead of creating many separate variables, you store values in a structure you can index and loop through. In Java, the two most common beginner-friendly options are arrays (fixed size) and ArrayList (dynamic size).

Arrays: Fixed-Size Containers

An array stores multiple values of the same type in a single variable. Arrays have a fixed length that you choose when you create them.

Declaring an Array

Declaration creates a variable that can reference an array, but does not create the array itself.

int[] scores;      // preferred style in Java for beginners

Creating (Initializing) an Array

You create an array with new and specify its length (number of elements). All elements get default values at first (0 for int, 0.0 for double, false for boolean, null for reference types).

scores = new int[5];   // 5 integers, all start as 0

You can also declare and create in one line:

Continue in our app.

You can listen to the audiobook with the screen off, receive a free certificate for this course, and also have access to 5,000 other free online courses.

Or continue reading below...
Download App

Download the app

double[] temps = new double[7];

Or initialize with known values using an array literal:

int[] ages = { 18, 21, 19, 20 };

Indexing: Accessing and Updating Elements

Array elements are accessed by index. Indexes start at 0, so the first element is index 0 and the last element is index length - 1.

int[] scores = new int[3];  // indexes: 0, 1, 2
scores[0] = 85;
scores[1] = 92;
scores[2] = 78;

int first = scores[0];      // 85

Array Length

Arrays have a public field named length (no parentheses). It tells you how many elements the array can hold.

int[] scores = { 85, 92, 78 };
int n = scores.length;  // 3

Looping Through an Array

The most common pattern is a for loop from 0 up to (but not including) array.length.

int[] scores = { 85, 92, 78 };
for (int i = 0; i < scores.length; i++) {
    System.out.println("Score at index " + i + ": " + scores[i]);
}

You can also use the enhanced for loop (for-each) when you only need the values, not the index.

int[] scores = { 85, 92, 78 };
for (int s : scores) {
    System.out.println(s);
}

Exercise: Store Test Scores and Compute Average/Min/Max

This exercise practices storing multiple values and scanning them to compute results.

Step-by-Step Plan

  • Create an int[] to store scores.
  • Fill the array with values (hard-coded or from input in your own practice).
  • Loop through the array to compute: sum, minimum, maximum.
  • Compute average as (double) sum / scores.length.

Example Implementation

int[] scores = { 88, 73, 95, 60, 84 };

int sum = 0;
int min = scores[0];
int max = scores[0];

for (int i = 0; i < scores.length; i++) {
    int s = scores[i];
    sum += s;

    if (s < min) {
        min = s;
    }
    if (s > max) {
        max = s;
    }
}

double avg = (double) sum / scores.length;

System.out.println("Average: " + avg);
System.out.println("Min: " + min);
System.out.println("Max: " + max);

Common Mistakes in This Exercise

  • Starting min/max at 0: If all scores are positive, min might incorrectly stay 0. Start with scores[0] instead.
  • Integer division: If you do sum / scores.length using ints, the result is truncated. Cast to double first.
  • Empty array: If the array could be empty, scores[0] is invalid. In beginner exercises, you usually ensure at least one element, but in real code you must check.

Common Array Errors (and How to Avoid Them)

Index Out of Bounds

The most frequent array bug is using an invalid index, which causes ArrayIndexOutOfBoundsException.

  • Valid indexes are from 0 to array.length - 1.
  • A loop condition must be i < array.length, not i <= array.length.
int[] scores = { 10, 20, 30 };

// Wrong: i <= scores.length will try scores[3]
for (int i = 0; i <= scores.length; i++) {
    System.out.println(scores[i]);
}

Correct version:

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

Confusing length with Last Index

scores.length is the number of elements, not the last index. The last index is scores.length - 1.

Trying to Resize an Array

Once created, an array cannot change its length. If you need a structure that grows or shrinks, use a collection such as ArrayList.

ArrayList: A Simple Dynamic Collection

ArrayList is a resizable list. You can add and remove items, and it automatically adjusts its size. It is part of java.util.

Creating an ArrayList

With generics, you specify the element type inside angle brackets. For example, a list of integers uses Integer (the wrapper type), not int.

import java.util.ArrayList;

ArrayList<String> names = new ArrayList<>();
ArrayList<Integer> scores = new ArrayList<>();

Adding Items

Use add to append to the end, or insert at a specific index.

ArrayList<String> names = new ArrayList<>();

names.add("Ava");
names.add("Noah");
names.add(1, "Mia");  // insert at index 1

Getting and Setting Items

Use get(index) to read and set(index, value) to replace.

String first = names.get(0);
names.set(0, "Eva");

Size of an ArrayList

Use size() (method) instead of length (array field).

int count = names.size();

Removing Items

You can remove by index or by value. Removing shifts later elements left, changing their indexes.

ArrayList<String> names = new ArrayList<>();
names.add("Ava");
names.add("Mia");
names.add("Noah");

names.remove(1);        // removes "Mia"
names.remove("Noah");  // removes the first matching "Noah"

Iterating Over an ArrayList

Use a standard for loop when you need indexes, or for-each when you only need values.

ArrayList<Integer> scores = new ArrayList<>();
scores.add(88);
scores.add(73);
scores.add(95);

for (int i = 0; i < scores.size(); i++) {
    System.out.println("Index " + i + ": " + scores.get(i));
}

for (int s : scores) {
    System.out.println("Score: " + s);
}

Exercise: Dynamic List of Scores (Add/Remove and Recompute Stats)

Step-by-Step Plan

  • Create an ArrayList<Integer> for scores.
  • Add several scores with add.
  • Optionally remove a score (by index or value).
  • Loop through the list to compute sum/min/max and average.

Example Implementation

import java.util.ArrayList;

ArrayList<Integer> scores = new ArrayList<>();
scores.add(88);
scores.add(73);
scores.add(95);
scores.add(60);
scores.add(84);

// remove a score by index (example)
scores.remove(3); // removes the 4th element (60)

int sum = 0;
int min = scores.get(0);
int max = scores.get(0);

for (int i = 0; i < scores.size(); i++) {
    int s = scores.get(i);
    sum += s;
    if (s < min) min = s;
    if (s > max) max = s;
}

double avg = (double) sum / scores.size();

System.out.println("Count: " + scores.size());
System.out.println("Average: " + avg);
System.out.println("Min: " + min);
System.out.println("Max: " + max);

Common ArrayList Errors

  • Using length instead of size(): ArrayList does not have length.
  • Index out of bounds: Valid indexes are 0 to size() - 1. After removing an element, indexes change.
  • Removing while iterating: If you remove items in a forward loop, you can skip elements because everything shifts left. A simple beginner-safe approach is to loop backward when removing by index.
// Removing all scores below 70 (beginner-safe pattern: loop backward)
for (int i = scores.size() - 1; i >= 0; i--) {
    if (scores.get(i) < 70) {
        scores.remove(i);
    }
}

Choosing Between Arrays and ArrayList

  • Use an array when you know the number of items will not change (for example, 12 months, 7 days, fixed number of sensors).
  • Use an ArrayList when the number of items can grow or shrink (for example, user-entered items, a list of tasks, search results).
  • Both support indexing and looping, but arrays use length and [], while ArrayList uses size(), get, and set.

Now answer the exercise about the content:

You need to store a list of scores where the number of items may grow or shrink as the program runs. Which approach is most appropriate, and why?

You are right! Congratulations, now go to the next page

You missed! Try again.

ArrayList is resizable, so it fits data that can change in length. You can add/remove items and use size() to loop safely, along with get() and set() for indexing.

Next chapter

Object-Oriented Programming Fundamentals in Java: Classes and Objects

Arrow Right Icon
Download the app to earn free Certification and listen to the courses in the background, even with the screen off.