Skip to lesson

An array is one variable that holds many values of the same type, like the marks of your 5 subjects. Each value sits in a numbered box, and the numbering starts at 0.

One name for many values

For the marks of 60 students you would need 60 variables, m1 to m60, and 60 lines to print them. An array keeps all the values under one name, made in one line.

Java
int m1 = 78;int m2 = 85;int m3 = 62;                          // ...one variable per mark
int[] marks = {78, 85, 62, 90, 71};   // one name, five values

int[] means "many ints". The values go inside { }, separated by commas. Creating an array (opens in a new tab) shows every way to make one.

Elements and indexes

You want only the Physics mark, the second one. Each value in an array is an element, and its position number is its index: the first index is 0, the second is 1, and so on.

The array marks holds 78, 85, 62, 90 and 71 in five boxes numbered 0 to 4. marks[0] is 78, the first box; marks[4] is 71, the last box. The last index is the size minus 1.

Example 1 · Marks of 5 subjects

MarksArray.javaJava
public class MarksArray {    public static void main(String[] args) {        int[] marks = {78, 85, 62, 90, 71};        System.out.println("Maths: " + marks[0]);        System.out.println("Physics: " + marks[1]);        System.out.println("English: " + marks[4]);   // the 5th mark    }}
Output
Maths: 78
Physics: 85
English: 71

What this code does

  • marks[0] reads the first element and marks[1] the second: the number in square brackets is the index.
  • Five elements have the indexes 0 to 4, so the last one is marks[4]. The last index is always one less than the size.
Think of the index as "how many steps from the start". The first box is 0 steps away, so its index is 0.

One type, fixed size

A weather app keeps the days and their temperatures. An array holds values of one type only, and its size is fixed when it is made: an array of 5 boxes always has 5 boxes.

Example 2 · A String array and a double array

Temperatures.javaJava
public class Temperatures {    public static void main(String[] args) {        String[] days = {"Mon", "Tue", "Wed"};        double[] temps = {31.5, 33.0, 29.8};        System.out.println(days[0] + ": " + temps[0]);        System.out.println(days[2] + ": " + temps[2]);    }}
Output
Mon: 31.5
Wed: 29.8

What this code does

  • days holds text, so its type is String[]; temps holds decimals, so it is a double[].
  • Index 2 of both arrays belongs to the same day: Wed and 29.8.

Need a sixth mark? Make a new array of size 6. A name and an age never share one array; keep them in two arrays that use the same index, as days and temps do.

Classify

Which array fits?

Tap a list of values, then tap the array type that can hold it.

Next step

Check your understanding

9 quick questions