What is an array?
14 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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.
int m1 = 78;int m2 = 85;int m3 = 62; // ...one variable per mark
int[] marks = {78, 85, 62, 90, 71}; // one name, five valuesint[] 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.
Example 1 · Marks of 5 subjects
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 }}Maths: 78 Physics: 85 English: 71
What this code does
marks[0]reads the first element andmarks[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.
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
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]); }}Mon: 31.5 Wed: 29.8
What this code does
daysholds text, so its type isString[];tempsholds decimals, so it is adouble[].- 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