Skip to content

Beginner · Arrays and strings · topic 11 of 60 · 25 min

Arrays

Explanation

An array holds a fixed number of values of one type, numbered from index 0 to length - 1. New arrays are filled with default values (0, false or null). Reading outside the range throws ArrayIndexOutOfBoundsException. java.util.Arrays gives toString, sort, fill, copyOf and equals. Arrays are objects, so assigning one to another variable shares it.

Why arrays?

Thirty students' marks in thirty separate variables is unmanageable. An array stores many values of the same type under one name, and a loop can process them all. Java arrays have a fixed length chosen when they are created; for lists that grow, you will use ArrayList (module 7).

java
int[] marks = new int[5];               // five ints, all 0
marks[0] = 78;
marks[1] = 92;
int[] prices = {499, 120, 2999};        // create and fill in one step
String[] cities = {"Delhi", "Pune"};
System.out.println(prices.length);      // 3 (a field, no brackets)
System.out.println(prices[2]);          // 2999
System.out.println(marks[4]);           // 0 (default value)

Default values

Element typeDefault
int, long, short, byte0
double, float0.0
booleanfalse
char'\u0000' (the null character)
String and any objectnull

Looping over arrays

java
int total = 0;
for (int i = 0; i < prices.length; i++) total += prices[i];   // when you need the index
for (int p : prices) System.out.println(p);                   // when you only need values
Careful: Index errors: valid indexes are 0 to length - 1. prices[3] on a 3-element array throws ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3. Most of these come from loops written with <= instead of <.

The Arrays helper class

java
import java.util.Arrays;

int[] a = {42, 7, 19};
System.out.println(a);                    // something like [I@1b6d3586 (not the contents!)
System.out.println(Arrays.toString(a));   // [42, 7, 19]
Arrays.sort(a);                           // sorts in place: [7, 19, 42]
int[] bigger = Arrays.copyOf(a, 5);       // [7, 19, 42, 0, 0]
int[] filled = new int[4];
Arrays.fill(filled, -1);                  // [-1, -1, -1, -1]
System.out.println(Arrays.equals(a, new int[]{7, 19, 42}));  // true
System.out.println(a == new int[]{7, 19, 42});               // false (different objects)

Arrays are objects

An array variable holds a reference. int[] b = a; does not copy the elements; both names point to the same array, so changing b[0] changes a[0]. To copy, use a.clone() or Arrays.copyOf(a, a.length). Passing an array to a method passes the reference, so the method can change the caller's elements.

java
int[] a = {1, 2, 3};
int[] b = a;          // same array
b[0] = 100;
System.out.println(a[0]);    // 100
int[] c = a.clone();  // independent copy
c[1] = 200;
System.out.println(a[1]);    // 2
Think of it like this: An array is like a row of numbered post-office boxes: a fixed number of boxes, each holding one letter of the same kind, numbered from 0. You cannot add a box later; you would rent a bigger row and move the letters.
Tip: Print arrays with Arrays.toString(arr) (or Arrays.deepToString for 2D arrays). Printing the array directly shows only its type and hash code.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Arrays · 1/6

Arrays

In this lesson you will store many values of one type in an array.

Prefer a video by a teacher? Find free videos on “java arrays tutorial Arrays.toString sort copyOf” on YouTube ↗

In real life: A week of temperature readings

A weather kiosk at a railway station stores the last seven daily maximum temperatures in an int array, then shows the average and the hottest day.

java
int[] temps = {34, 36, 38, 35, 41, 39, 37};
int sum = 0, hottest = 0;
for (int i = 0; i < temps.length; i++) {
    sum += temps[i];
    if (temps[i] > temps[hottest]) hottest = i;
}
System.out.printf("Average %.1f, hottest on day %d (%d°C)%n", sum / 7.0, hottest + 1, temps[hottest]);
Prints Average 37.1, hottest on day 5 (41°C).

Practice (0/3 done)

Task 1 · Question

What does this print? int[] a = new int[3]; a[1] = 5; System.out.println(Arrays.toString(a));

Task 2 · Question

What does this print? int[] x = {1, 2, 3}; int[] y = x; y[2] = 9; System.out.println(x[2] + x.length);

Task 3 · Practice

Write MarksReport.java with an int array of 8 marks. Print the array with Arrays.toString, the total, the average with 2 decimals, the highest and lowest marks, and how many students scored 60 or more.

Quick quiz

Question 1

1.What is the index of the last element of an array a?

Question 2

2.What is the default value of elements in new String[4]?

Question 3

3.How do you get the length of an array arr?

Question 4

4.Which compares the CONTENTS of two int arrays?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What is the index of the last element of an array a?

Answer: a.length - 1

Indexes run from 0 to length - 1.

What is the default value of elements in new String[4]?

Answer: null

Object elements default to null.

How do you get the length of an array arr?

Answer: arr.length

For arrays, length is a field (no brackets). Strings use length().

Which compares the CONTENTS of two int arrays?

Answer: Arrays.equals(a, b)

== and array.equals compare references.

What is the index of the last item in an array of length 8?Related

Answer: 7

Indexes go from 0 to Length - 1.

From Arrays: one name, many values

Which copies array a (3 ints) into array b?Related

Answer: memcpy(b, a, sizeof a);

Arrays cannot be assigned; copy the bytes or loop.

From Arrays

What is the index of the LAST element of an array of size 10?Related

Answer: 9

Indexes run from 0 to size - 1.

From Arrays, std::array and a first look at std::vector

What is the type of [...]int{1, 2, 3}?Related

Answer: [3]int

... asks the compiler to count the elements, so it is an array of length 3.

From Arrays and slices

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 4 more topics in “Arrays and strings” before its exam: Two-dimensional arrays and array algorithms, Strings in depth, StringBuilder and formatting, Wrapper classes and autoboxing.
  2. Module 3 exam: Arrays and strings · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Classes and objects. 60 topics left in the course before the final exam.

← Previous: Reading errors and debugging