Java chapters

Chapter 10 of 17

Arrays and Collections

Try this in our Java Compiler →

Storing many values

A single variable holds one value, but most programs deal with lists of things: users, orders, scores. Java provides a built-in collection type — usually called an array or list — that holds many values under a single name and indexes them with a number starting at 0.

int[] nums = {10, 20, 30};
for (int n : nums) System.out.println(n);

import java.util.ArrayList;
ArrayList<Integer> list = new ArrayList<>();
list.add(40);

Common operations

You will spend a lot of time looping over collections, adding items, removing items, searching for an item, sorting, and transforming each element into something else. Learn your language's standard library helpers for these tasks — they are faster and clearer than hand-written loops.

Other collection types

Beyond arrays, Java usually offers sets (no duplicates), maps (key → value pairs) and queues / stacks. Choosing the right collection for the job makes your code shorter and your program faster.

Details for java

Conditions must be boolean, not zero or nonzero. String.equals compares contents; == compares references. Short-circuit && can protect a null access. Arrays have fixed length while ArrayList grows.

Practice and verify

Change one meaningful value in the example and predict the result before running. Then test a boundary or empty value. Explain what changed and why, rather than only copying the output.

Try it yourself

Output
Run your project to see output here.
Ctrl/Cmd+Enter runs · Ctrl/Cmd+S downloads the project · Local auto-save is always on