BeginnerLesson 6 of 204 min read

Arrays: Fixed-Size Lists, Sorting and Searching

Learn to create, fill, sort and search arrays, use two-dimensional arrays, and see what happens when an index is out of range, with results checked independently.

In this lesson you will

  • Create and fill arrays
  • Sort and search with Arrays
  • Use a two-dimensional array
  • Handle an out-of-range index

About 28 minutes

Twelve bikes and seven days

Hana keeps a rating for each of her 12 bikes, and a grid that shows which bikes are booked on which day of the week. A variable that holds one number is not enough for this, and an array is the simplest answer. An array is a fixed-size row of values of the same type, numbered from zero. Its size is set when you create it and can never change, which is both its strength, because it is fast and predictable, and its limit, which is why collections in lesson 10 exist.

You create an array with new, as in new int[5], or with a list of values in braces. Numbers start as 0, booleans as false and objects as null. You read element i with a[i], and the length is a.length without brackets. The index of the last element is length minus one, and going outside the array throws an ArrayIndexOutOfBoundsException, which is Java’s way of stopping a bug at the moment it happens, rather than reading memory that does not belong to you. The class java.util.Arrays has helpers for printing, sorting, searching and copying.

Task Code
Create int[] a = new int[5];
Fill with values int[] a = {4, 9, 2};
Length a.length
Print Arrays.toString(a)
Sort Arrays.sort(a)
Search a sorted array Arrays.binarySearch(a, 9)
Copy Arrays.copyOf(a, 10)
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] ratings = {4, 9, 2, 7, 5, 8, 3, 9, 6, 1, 7, 10};
        System.out.println("length: " + ratings.length + ", first: " + ratings[0] + ", last: " + ratings[ratings.length - 1]);
        int sum = 0, best = ratings[0];
        for (int r : ratings) { sum += r; if (r > best) best = r; }
        System.out.println("sum " + sum + ", average " + (double) sum / ratings.length + ", best " + best);
        int[] sorted = Arrays.copyOf(ratings, ratings.length);
        Arrays.sort(sorted);
        System.out.println("sorted: " + Arrays.toString(sorted));
        System.out.println("original untouched: " + Arrays.toString(ratings));
        System.out.println("index of 8 in the sorted copy: " + Arrays.binarySearch(sorted, 8));
        boolean[][] booked = new boolean[3][7];
        booked[0][2] = true; booked[0][5] = true; booked[1][5] = true; booked[2][0] = true;
        int count = 0;
        for (boolean[] bike : booked) for (boolean b : bike) if (b) count++;
        System.out.println("bookings in the grid: " + count + " (3 bikes x 7 days = " + booked.length * booked[0].length + " slots)");
        String[] names = new String[2];
        System.out.println("default string element: " + names[0] + ", default int: " + new int[1][0]);
        try {
            System.out.println(ratings[12]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("caught: " + e.getMessage());
        }
    }
}
length: 12, first: 4, last: 10
sum 71, average 5.916666666666667, best 10
sorted: [1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 9, 10]
original untouched: [4, 9, 2, 7, 5, 8, 3, 9, 6, 1, 7, 10]
index of 8 in the sorted copy: 8
bookings in the grid: 4 (3 bikes x 7 days = 21 slots)
default string element: null, default int: [[I@27716f4
caught: Index 12 out of bounds for length 12

The 12 ratings add up to 71, so the average is 5.9167, and the best rating is 10. After copying and sorting, the original array was untouched, because Arrays.copyOf made a separate array, which is worth remembering: assigning one array variable to another, with =, copies only the reference. Binary search on the sorted copy found the value 8 at index 8, and it only works on a sorted array, since it repeatedly halves the range. The grid of 3 bikes by 7 days holds 21 slots, and 4 of them are marked booked.

The last test shows the safety net. Reading ratings[12] on an array of length 12 does not return garbage. Java stopped it with the message “Index 12 out of bounds for length 12”, which tells you both the bad index and the length. You can catch the exception, as the program did, but in most cases the right fix is to correct the loop, since the exception is a symptom of a counting mistake. Two-dimensional arrays are arrays of arrays: booked[1][5] reads the row for bike 1 and then the entry for day 5, and each row could even have a different length.

Check by hand: 4 + 9 + 2 + 7 + 5 + 8 + 3 + 9 + 6 + 1 + 7 + 10 = 71, and 71 divided by 12 is 5.9167. In the sorted array 1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 9, 10 the value 8 sits at position 8 when counting from zero. An independent Python calculation of the same sums and the same sorted list agreed with every number printed.

Index 0 is the first element

The valid indexes of an array of length n are 0 to n – 1. Loops with i <= a.length run one step too far.

Use for-each when you do not need the index

for (int r : ratings) is shorter and cannot go out of range. Use an index loop only when you need the position.

About this course

Every program in this lesson was compiled and run with OpenJDK 21 while the course was written. Java releases twice a year, so check the official Java documentation for the current version and for features added after Java 21.

Practice

Create an array of the prices for the seven days, find the cheapest and the most expensive day, and print the days in order of price. Then create a 12 by 7 grid for all bikes and mark five bookings of your choice.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What is the index of the first element?

  1. 1
  2. -1
  3. 0
  4. The length

Arrays are zero-based.

What happens if you read an index past the end?

  1. You get zero
  2. An exception is thrown
  3. You get the first element
  4. The program continues silently

ArrayIndexOutOfBoundsException.

Does b = a copy the array a?

  1. Yes, all values
  2. No, it copies only the reference
  3. Only the first value
  4. It sorts it

Use Arrays.copyOf for a real copy.

When does binary search work?

  1. On a sorted array
  2. On any array
  3. Only on strings
  4. Only on booleans

It halves the range each step.

What is booked[1][5]?

  1. Row 1, column 5 of a 2D array
  2. A string
  3. A method
  4. A class

An array of arrays.

Summary

  • Arrays are fixed-size, zero-based rows of one type.
  • Arrays.sort and Arrays.binarySearch sort and search.
  • Out-of-range indexes throw an exception.
  • Copy with Arrays.copyOf, not with =.

Next lesson

Lesson 7 turns to classes and objects, where your own types begin.

Questions

Can I change the size of an array?

No. Create a new array and copy the values, or use an ArrayList, which lesson 10 covers.

What does Arrays.toString do?

It turns an array into a readable text. Printing an array directly shows only a type and a hash code.

What is the default value of an int array?

Zero. Boolean arrays start false and object arrays start null.

Progress is saved in this browser.