New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› Java› Arrays and ArrayLists

Arrays and ArrayLists

💻 Java

Store fixed-size arrays and resizable lists, then loop through them safely.

Lesson 5 of 9 Tutorial
0 of 9 completed

Arrays hold a fixed number of values. ArrayList grows as needed and is usually the better default for collections.

By the end of this lesson you can:
  • Create and iterate arrays.
  • Use ArrayList methods.
  • Avoid index errors.

Arrays

An array has a fixed length set at creation. Indexes start at zero and end at length minus one.

int[] scores = {88, 74, 91, 65};

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

for (int score : scores) {
    System.out.println(score);
}

ArrayList

ArrayList resizes automatically. Import it from java.util and use wrapper types such as Integer instead of primitives.

import java.util.ArrayList;

ArrayList<String> subjects = new ArrayList<>();
subjects.add("Mathematics");
subjects.add("English");
subjects.add("Physics");

System.out.println(subjects.size());
System.out.println(subjects.get(0));
subjects.remove("English");

Common Mistakes

Accessing an index equal to the length throws ArrayIndexOutOfBoundsException. Removing items while looping over a list can skip elements; iterate over a copy or use an iterator.

Warning Arrays have a length field, lists have a size() method. Mixing them up is a common source of compile errors.

Practice

  1. Create an array of five scores and print the highest.
  2. Add three names to an ArrayList and print them.
  3. Remove one item and print the new size.

Hands-on exercise

Write a program with an int array of six scores.
1. Calculate the average.
2. Print the average to one decimal place.
3. Print every score above the average.

Recap

Arrays are fixed and fast. ArrayList is flexible and easier for most application work.

Example

int[] scores = {88, 74, 91, 65};

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

for (int score : scores) {
    System.out.println(score);
}

Exercises

Exercise 1. Average score Medium
Write a program with an int array of six scores.
1. Calculate the average.
2. Print the average to one decimal place.
3. Print every score above the average.
Java exercise-1.java
Expected Output
Average: 74.8 followed by the scores above it.

Lesson Nav

Lesson sections