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.

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

import java.util.ArrayList; ArrayList 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.

Try it yourself

Java Compiler
Output
Code runs on the Play with Coding execution engine — your code is saved locally for next time.