Computer Fundamentals and Introduction to Programming · Lecture Notes

Chapter 10: Arrays

Declaring 40 separate variables to store the grades of 40 students in a class is both tedious and error-prone, and when the number of grades changes the program has to be rewritten. An array solves this problem: it holds many values of the same type under a single name, in numbered cells. These notes begin with the structure of an array in memory. They then cover declaring arrays, reaching elements by index, and traversing an array with loops. Basic operations such as the sum, the average, the largest and smallest values, reversing, counting frequencies and the sieve of Eratosthenes are traced step by step. Copying, the Arrays class, passing arrays to methods, and how searching and sorting are written in Java follow. The last sections deal with two-dimensional arrays, matrix operations and common mistakes with arrays. All the programs shown in the notes were compiled and run with JDK 21, and the console output and error messages are taken verbatim from those runs.

Learning outcomes

Creation
Declare arrays and create them with new and with an initializer; explain that an array variable holds a reference and that cells receive default values.
Access
Reach elements by index and use the length field correctly; recognize the cause and the message of an out-of-bounds error.
Processing
Traverse an array with the classic and the enhanced for; write sum, average, maximum–minimum, reversing, counting, copying, searching and sorting in Java and state their costs.
Matrices
Do row–column operations with two-dimensional arrays; explain jagged arrays and the shallow-copy trap; code the transpose and matrix multiplication.

10.1The concept of an array

In the programs so far, each value has lived in its own variable: int grade1, int grade2, int grade3. For three grades this works. For forty grades, forty variables are needed, and finding their average means writing a sum with forty terms. If the number of grades rises to forty-one, the program has to be changed. The source of the problem is that the variables are independent of one another. The program cannot say “the third grade” or “the next grade”, because variable names are text, not numbers.

10.1.1What is an array?

Definition 10.1

An array is a data structure that stores a fixed number of values of the same type in a single object, in consecutive cells. The values in the cells are called elements. Each element is reached by its index, the sequence number of its cell. In Java, indices start at 0. The number of cells is the length of the array; the length is fixed when the array is created and cannot change afterward.

Each of the three conditions in the definition has a reason. The same type condition makes every cell the same size: each cell of an int array holds 4 bytes. The fixed number condition allows the array to occupy memory as one contiguous block. Consecutive cells make it possible to find the location of any element with a single calculation.

In Java, an array is an object. Objects are created in the region of memory called the heap. The local variables of methods, in contrast, are kept in a separate region called the stack. An array variable lives on the stack, but it does not contain the elements. The variable stores the reference to the array object on the heap, that is, a value that shows where the object is in memory. In the figures a reference is drawn as an arrow.

StackHeapnums0010203040length = 5 (fixed)same type: all int
Figure 10.1: Memory after int[] nums = new int[5];. The variable nums on the stack points to the five-cell array object on the heap. The cells are numbered 0 to 4, all have the same type (int), and all start with the value 0. The length is 5 and does not change.

Figure 10.1 shows this separation. The box on the left is the variable itself; it contains only an arrow, that is, a reference. The five cells on the right are the array object. At first this separation looks like an unnecessary detail. Yet most of the surprising behavior of arrays comes from it. Two variables can point to the same array; when an array is passed to a method, the method can change the original array; and the == operator compares the references of two arrays, not their contents. Each of these behaviors is worked through with an example in later sections.

10.1.2Index and address calculation

The elements of an array are reached by writing the index in square brackets. a[0] is the first element and a[1] the second. In an array of five elements, the last element is a[4]. The general rule is this: for an array of length n, the first index is 0 and the last is n − 1. In Java the length of an array is read with a.length, so the last element can always be written as a[a.length - 1].

010120230340450aa.length = 5first: a[0]last: a[a.length − 1] = a[4]a[2] → 30
Figure 10.2: The array a with five elements: 10, 20, 30, 40, 50. Indices run from 0 to 4 and a.length is 5. The first element is a[0] and the last is a[a.length − 1], that is, a[4]. The highlighted cell is a[2], and its value is 30.

Starting the index at 0 feels strange to beginners. In everyday life, counting starts at 1. In Java, in C and in many other languages, however, the index is really an offset: it says how many cells to move forward from the start of the array. The first element is at the start, so its offset is zero. a[2] is two cells away from the start.

This interpretation also explains why access is fast. Because an array consists of consecutive cells in memory, the address of cell number i is computed with a single formula:

address(a[i]) = start address + i × cell size

Example 10.1

Suppose the start address of an int array on the heap is 1000. Since an int takes 4 bytes, the cell size is 4. What is the address of a[3]?

In the formula i = 3 and the cell size is 4: 1000 + 3 × 4 = 1000 + 12 = 1012. The processor goes directly to this address and reads the value. The cells a[0], a[1] and a[2] are never looked at. The same calculation for a[999] is also a single multiplication and a single addition: 1000 + 999 × 4 = 4996.

The size of the calculation does not depend on the length of the array. An array of five elements and one of a million elements both need one multiplication and one addition. This is why the cost of access by index is constant time, written O(1) in big-O notation. Big-O notation summarizes how the running time of an operation grows as the input grows. O(1) means “the same time however large the input”, while O(n) means “the time grows in proportion to the number of elements”. In a real Java program the start address is not shown to the programmer, and the JVM additionally checks on every access that the index is valid. But the principle of the calculation is the same.

10.1.3Strengths and weaknesses of arrays

The structure of an array gives it some advantages and also sets some limits. Both come from the same source: fixed-size, consecutive cells.

Table 10.1: Advantages and limits of arrays.
AdvantageLimit
Fast access by indexThe size is fixed
Element type is consistentInserting in the middle is costly
Easy to process with loopsGoing out of bounds is a runtime error
Orderly layout in memoryHolds only one element type

In the table, “element type is consistent” and “holds only one element type” are two sides of the same property. The compiler prevents text from being put into an int array by mistake, which is a guarantee. On the other hand, it is impossible to keep a student's name, number and grade in the same array; that takes three separate arrays or another structure.

Access by index: a direct jump100201302403504address = start + 3 × cell sizea[3] → 40: one step, O(1)Insert in the middle: 15 → index 1102030401015203040the 3 elements on the rightshift by one eachIf the array is full: new, larger array + copying (the size is fixed)
Figure 10.3: Left: access by index, where a[3] is reached in one step by an address calculation. Right: inserting in the middle, where 20, 30 and 40 are each shifted one cell to the right to put 15 at position 1. If the array is full, a new, larger array must be created and all the elements copied.

The right half of Figure 10.3 shows why inserting in the middle is expensive. Suppose 15 is to be placed between 10 and 20 in the array {10, 20, 30, 40}. Because the cells are consecutive, there is no operation “slip a cell in between”. 40 moves one place to the right, then 30, then 20, and 15 is written into the cell that has been freed, number 1. The number of elements shifted equals the number of elements after the insertion point. In the worst case, inserting at the front, all the elements move. This is why inserting and deleting in the middle cost O(n). Moreover, if there is no free cell at the end of the array, the insertion cannot be done at all: the length is fixed. A new, larger array is created and the old elements are copied into it.

10.2Declaring and creating arrays

Using an array takes two separate jobs. First the array variable is declared, which opens a reference box on the stack. Then the array object is created and its reference is written into that box. The two jobs can be done on one line or on separate lines.

10.2.1Declaration and new

In Java, an array type is written by adding a pair of square brackets after the element type: int[] means “array of int”, String[] “array of String” and double[] “array of double”. The array object is created with the new operator, and the length is given in square brackets. The following program shows four separate declarations together:

public class Declaration {
    public static void main(String[] args) {
        int[] nums = new int[5];
        String[] names = {"Ada", "Can", "Ece"};
        double[] readings;
        readings = new double[10];
        System.out.println(nums.length + " " + names.length + " " + readings.length);
    }
}
5 3 10

Let us examine the lines in order.

  1. int[] nums = new int[5]; does the declaration and the creation on one line. new int[5] creates an int array of five cells on the heap. The assignment writes the reference of this array into the variable nums.
  2. String[] names = {"Ada", "Can", "Ece"}; creates the array together with its values. No length is written; the compiler counts the values and makes the length 3.
  3. double[] readings; only declares the variable. At this point there is no array on the heap.
  4. readings = new double[10]; creates the ten-cell array later and writes its reference into the variable.

The length does not have to be a constant; it can also be an int computed while the program runs. new int[n] creates as many cells as the current value of n. The length can be 0; such an array is called an empty array and has no cells. A negative length causes a NegativeArraySizeException when the program runs. Once an array has been created, its length cannot be changed. If new double[20] is later assigned to readings, the old array does not grow; the variable starts pointing to a new, separate array.

Common mistake

Declaring the variable and using it without creating the array. If nums[0] = 7; is written after the line int[] nums;, there are no cells. Java catches this at compile time:

Unassigned.java:4: error: variable nums might not have been initialized
        nums[0] = 7;
        ^
1 error

The message says “the variable nums might not have been assigned a value”. The fix is an assignment such as nums = new int[4]; before use.

10.2.2Default values

The cells of an array created with new are not left empty. Java writes the default value of the element type into every cell. For numeric types this value is zero, and for boolean it is false. For object types, such as String, the default value is null. null is the special value meaning “this reference does not point to any object”.

int[] a = new int[3];000double[] d = new double[3];0.00.00.0boolean[] b = new boolean[3];falsefalsefalseString[] s = new String[3];nullnullnull
Figure 10.4: Initial values of three-cell arrays created with new: 0 for int, 0.0 for double, false for boolean and null for String.

The program below prints the values in Figure 10.4 to the console. The default value of a char array has been added:

public class Defaults {
    public static void main(String[] args) {
        int[] a = new int[3];
        double[] d = new double[2];
        boolean[] b = new boolean[2];
        String[] s = new String[2];
        char[] c = new char[2];
        System.out.println(a[1] + " " + d[0] + " " + b[1] + " " + s[0]);
        System.out.println((int) c[0]);
        System.out.println(a.length + d.length + s.length);
    }
}
0 0.0 false null
0
7

The first line prints one cell from each of four different arrays: 0, 0.0, false and null. The default value of a char array is the character whose code is 0. Because this character is invisible on the screen, it is printed as a number with an (int) cast. The last line contains a trap. The expression a.length + d.length + s.length contains no string, so + performs addition and the result is 3 + 2 + 2 = 7.

The default-value rule applies only to array cells and class fields. Java does not give a value on its own to local variables declared inside a method. int x; System.out.println(x); does not compile. By contrast, a cell of an array created with new int[1] always starts at 0.

10.2.3The initializer

If the values of the elements are known in advance, the array is created by writing the values inside curly braces. This notation is called an array initializer: int[] scores = {70, 85, 90};. No length is written, because the compiler counts the values. Here the length is 3.

The short form of the initializer can be used only on the declaration line. It cannot be used to assign later to a variable that was declared earlier:

public class InitError {
    public static void main(String[] args) {
        int[] a;
        a = {1, 2, 3};
    }
}
InitError.java:4: error: illegal start of expression
        a = {1, 2, 3};
            ^
InitError.java:4: error: not a statement
        a = {1, 2, 3};
             ^
InitError.java:4: error: ';' expected
        a = {1, 2, 3};
              ^
3 errors

The compiler gives three messages for a single mistake. In such a flood of messages, the first message is the one to go by: “illegal start of expression”. The correct way is to put the array type in front of the initializer: a = new int[]{1, 2, 3};. This long form is also used to pass an array directly to a method: search(new int[]{2, 4, 6, 8}, 5).

Java accepts both spellings of an array variable: int[] a and int a[]. The second is a leftover from the C language. These notes and the slides use the first form, because the type information (int[]) stays in one piece.

10.2.4Creating an array step by step

The program below first declares an array, then creates it, writes values into two of its cells, and prints the lengths of two arrays:

public class Create {
    public static void main(String[] args) {
        int[] nums;
        nums = new int[4];
        nums[0] = 7;
        nums[3] = 2;
        String[] names = {"Ada", "Can", "Ece"};
        System.out.println(nums.length + " "
                           + names.length);
    }
}
4 3

Table 10.2 shows what is on the stack and the heap at each step of the program.

Table 10.2: The trace table of the Create program. “?” marks a variable that has not been given a value yet.
LineStackHeapExplanation
int[] nums;nums = ?—Only the reference variable is created
nums = new int[4];nums → array 1array 1: [0, 0, 0, 0]Four cells, all 0
nums[0] = 7;samearray 1: [7, 0, 0, 0]Follow the arrow, write 7 into cell 0
nums[3] = 2;samearray 1: [7, 0, 0, 2]Last cell: index length − 1 = 3
String[] names = {…};names → array 2array 2: [Ada, Can, Ece]Three values, length 3
println(…)samesameOutput: 4 3
Stack (variables)Heap (objects)00102030length = 4nums
Stack (variables)Heap (objects)07102032length = 40Ada1Can2Ecelength = 3numsnames
Figure 10.5: Two moments of the trace. Top: after new int[4], four zero cells have been created on the heap and the reference has been written into the variable nums. Bottom: the end of the program, where nums points to the array [7, 0, 0, 2] and names to the array of three strings.

The first row of the table deserves attention: when int[] nums; runs, nothing happens on the heap. Figure 10.5 shows this emptiness and the change that follows. The new in the second line creates the object on the heap, and the assignment operator writes the reference into the variable. After that, every access such as nums[0] = 7 follows the same path: the arrow in the variable is followed, the array on the heap is reached, the cell is found by its index and the value is written.

In the last line, nums.length and names.length are read. length is not a method but a field of the array, so it is written without parentheses. In the String class, by contrast, the length is obtained with the length() method. This difference is often confused: writing a.length() for an array or s.length for a string is a compile-time error. The length field is read-only; nums.length = 10; does not compile either.

10.3Accessing elements

10.3.1Reading and writing

An array element is used like an ordinary variable. If scores[1] appears inside an expression, the value in the cell is read. If it appears on the left of an assignment, the cell itself is meant and a new value is written into it. The index inside the square brackets does not have to be a constant; any expression that gives an int can be an index: a[i], a[i + 1], a[a.length - 1].

public class Reading {
    public static void main(String[] args) {
        int[] scores = {70, 85, 90};
        int first = scores[0];
        scores[1] = 88;
        int last = scores[scores.length - 1];
        System.out.println(first + " " + last);
    }
}
70 90
Table 10.3: The trace table of the Reading program.
LinescoresfirstlastExplanation
1[70, 85, 90]——Three elements; indices 0, 1, 2
2[70, 85, 90]70—Reading: scores[0] → 70
3[70, 88, 90]70—Writing: 85 is erased, 88 is written
4[70, 88, 90]7090scores.length - 1 = 3 − 1 = 2
5[70, 88, 90]7090Output: 70 90
Stack (variables)Heap (objects)070188290length = 3scoresfirst70last90
Figure 10.6: Memory at the end of the Reading program. first and last are ordinary int variables; their values were copied from the array. Cell 1 of the array now holds 88.

The expression scores[scores.length - 1] on line 4 is the general way to read the last element. First the inner expression is computed: 3 − 1 = 2. Then scores[2] is read. If the array had five elements, the same line would read scores[4] without any change. Writing the last index by hand (scores[2]), on the other hand, silently gives the wrong element when the array grows.

Figure 10.6 also shows an important detail: int first = scores[0]; copies the value out of the array. After this line, even if scores[0] changes, first stays 70. For primitive types (int, double, boolean, char), assignment always copies the value.

10.3.2The out-of-bounds error

Valid indices are the integers from 0 to length − 1. A negative index, or length itself, is invalid. Access with an invalid index stops the program in Java with an ArrayIndexOutOfBoundsException. This is an exception: an error condition that arises while the program is running and interrupts the normal flow.

0418263143-1✗5✗valid: 0 … length − 1 = 4a[-1]a[5]a.length = 5 but a[5] DOES NOT EXIST → ArrayIndexOutOfBoundsException
Figure 10.7: In an array of five elements the valid indices are 0…4. The cells a[-1] to the left of the array and a[5] to the right do not exist. a.length is 5, but there is no cell called a[5].
Definition 10.2

In an array of length n, access with an index i that does not satisfy 0 ≤ i ≤ n − 1 is an out-of-bounds access. Java checks this condition on every array access; if it is not satisfied, an ArrayIndexOutOfBoundsException is thrown.

The compiler usually cannot catch this error, because the index is often computed while the program runs. The following program compiles without any problem:

public class Negative {
    public static void main(String[] args) {
        int[] a = {4, 8, 6};
        System.out.println(a[-1]);
    }
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3
	at Negative.main(Negative.java:4)

The message gives three pieces of information. The type of the error is ArrayIndexOutOfBoundsException. The detail part says “Index -1 out of bounds for length 3”: index −1 is outside the bounds of an array of length 3. The last line shows where the error occurred: line 4 of the file Negative.java. This check does not exist in languages like C, where an out-of-bounds write can silently corrupt a part of memory that belongs to another variable. Java's check has a cost, but it catches the error at exactly the right place.

10.3.3One iteration too many: step by step

The most common source of out-of-bounds errors is writing <= instead of < in the loop condition. The error is called an off-by-one error:

public class Bounds {
    public static void main(String[] args) {
        int[] a = {4, 8, 6};
        for (int i = 0; i <= a.length; i++) {
            System.out.println(a[i]);
        }
    }
}
> java Bounds
4
8
6
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
	at Bounds.main(Bounds.java:5)
Table 10.4: The trace table of the Bounds program (a.length = 3).
Iterationii <= a.lengthActionOutput
100 <= 3 → truea[0] is printed4
211 <= 3 → truea[1] is printed8
322 <= 3 → truea[2] is printed6
433 <= 3 → truea[3]: no such cellexception
0418263nonea▲ i
Figure 10.8: In the fourth iteration i = 3. Because the condition 3 <= 3 is true, the body is entered, but there is no cell number 3.

The first three iterations are fine and 4, 8, 6 are printed. In the fourth iteration i becomes 3. The condition 3 <= 3 is true, the body is entered and an attempt is made to read a[3] (Figure 10.8). The program stops at this point. Note that the error does not erase the earlier output: 4, 8 and 6 stay on the console. This is why a faulty program can look “almost right”.

The fix is to make the condition i < a.length. Then, when i is 3, 3 < 3 is false and the loop ends without entering the body. The rule to remember is short: if the index starts at 0, the condition is < length. <= length - 1 is also correct, but longer and more error-prone.

10.4Traversing with loops

The real power of an array appears when it is combined with a loop. Because the index can be a variable, a single loop can visit all the elements of the array in turn. Visiting every element of an array once is called traversal. Java has two ways to traverse: the classic for and the enhanced for.

10.4.1The classic for

In the classic for loop, a counter, usually i, starts at 0 and increases by 1 on each iteration. Because the condition is i < array.length, the counter runs over exactly the valid indices:

public class Classic {
    public static void main(String[] args) {
        int[] scores = {70, 88, 90};
        for (int i = 0; i < scores.length; i++) {
          System.out.printf("%d: %d%n", i, scores[i]);
        }
    }
}
0: 70
1: 88
2: 90

printf does formatted printing: the first %d in the pattern is replaced by i, the second %d by scores[i], and %n ends the line. The trace of the loop is given in Table 10.5.

Table 10.5: The trace table of the Classic program.
ii < 3scores[i]Line printed
0true700: 70
1true881: 88
2true902: 90
3false—loop ends

The last row is important: when i is 3, the condition is false and scores[3] is never accessed. The condition is tested at the start of every iteration, before the body. So it is no problem for i to reach an invalid value; the problem is entering the body with an invalid value.

The structure of the classic for is flexible. By changing the start, the condition and the step, the array can be traversed in different ways. for (int i = a.length - 1; i >= 0; i--) traverses the array from the end to the start. A step of i += 2 advances by skipping one element. This flexibility comes from controlling the index directly.

10.4.2The enhanced for

In many traversals the index itself is not needed; only the values of the elements are. Java has a shorter loop for these cases.

Definition 10.3

The enhanced for (also called for-each) is a loop written in the form for (T x : array). The loop goes through the elements of the array in order from start to end; on each iteration it puts a copy of the next element into the variable x. The loop has no index.

The notation reads “for each x in the array”. To the left of the colon is a variable with the element type, and to the right is the array. The word “copy” in the definition explains the behavior of the following program:

public class Enhanced {
    public static void main(String[] args) {
        int[] scores = {70, 88, 90};
        for (int score : scores) {
            score = score + 5;
            System.out.println(score);
        }
        System.out.println(scores[0]);
    }
}
75
93
95
70
Table 10.6: The trace table of the Enhanced program. The array does not change at any step.
IterationCell copiedscore (before → after)scoresOutput
1scores[0]70 → 75[70, 88, 90]75
2scores[1]88 → 93[70, 88, 90]93
3scores[2]90 → 95[70, 88, 90]95
last—out of scope[70, 88, 90]70
070188290scoresscore75copy
Figure 10.9: In the first iteration the 70 in scores[0] is copied into the variable score. score = score + 5 only makes the copy 75; the cell in the array stays 70.

On each iteration score is increased by five and printed: 75, 93, 95. The last line prints 70. The array has not changed at all. Figure 10.9 shows why: score is not the cell itself but a separate variable. The value in the cell is copied into it at the start of each iteration. An assignment to the copy is not written back into the array. When the loop ends, the variable score also goes out of scope.

To really change the array, you must write into the cell by index. This calls for the classic for:

import java.util.Arrays;

public class AddFive {
    public static void main(String[] args) {
        int[] scores = {70, 88, 90};
        for (int i = 0; i < scores.length; i++) {
            scores[i] = scores[i] + 5;
        }
        System.out.println(Arrays.toString(scores));
    }
}
[75, 93, 95]

In this program, scores[i] is on the left of the assignment; the value is written directly into the cell. Arrays.toString prints all the elements of the array inside square brackets. This method is in the java.util.Arrays class and is imported at the top of the program.

Common mistake

Trying to update the array with the enhanced for. for (int x : a) x = x * 2; compiles and runs, but the array stays the same. The compiler does not even warn, because assigning to the loop variable is allowed by the language rules. The mistake is noticed only when the output is examined.

10.4.3Which loop when?

The two loops cannot always be used in place of each other. The choice is decided by whether the job needs the index.

Table 10.7: The classic and the enhanced for compared.
JobClassic forEnhanced for
Reading elements to add up, count or printWorksWorks and is shorter
Printing the position of an elementWorksNot possible (no index)
Writing a new value into a cellWorksNot possible (the variable is a copy)
Looking at a neighboring element (a[i + 1])WorksNot possible
Traversing backward or skippingWorksNot possible (always start to end)
Traversing two arrays together with the same indexWorksNot possible

The enhanced for is as safe as it is short: because there is no index, an out-of-bounds error cannot occur. For this reason it is preferred for traversals that only read. When an index is needed, switch to the classic for.

10.5Basic array operations

The operations in this section are the building blocks of most programs written with arrays. In each of them the same question is asked: how many times must the array be traversed, and what information must be kept while traversing? All the examples run in O(n) time, because each element is looked at a constant number of times.

10.5.1Sum and average

To find a sum, an accumulator variable is used. The accumulator starts at 0, the identity of addition, and each element is added to it:

public class Sum {
    public static void main(String[] args) {
        int[] nums = {4, 7, 2, 6};
        int sum = 0;
        for (int value : nums) sum += value;
        double avg = 0;
        if (nums.length > 0)
            avg = (double) sum / nums.length;
        System.out.println(sum + " " + avg);
        System.out.println(sum / nums.length);
    }
}
19 4.75
4
Table 10.8: The trace table of the Sum program.
Stepvaluesumavg
Start—0—
Iteration 140 + 4 = 4—
Iteration 274 + 7 = 11—
Iteration 3211 + 2 = 13—
Iteration 4613 + 6 = 19—
double avg = 0;—190.0
4 > 0 → division—1919.0 / 4 = 4.75

The average has two details. The first is the (double) cast. sum and nums.length are both int; the quotient of two ints is integer division, and the fractional part is discarded. The last line of the program shows this: sum / nums.length gives 4. The cast converts sum to double before the division; the division is then done in floating point and gives 4.75. The second is the if (nums.length > 0) check. In an empty array the length is 0. In floating-point division, 0.0 / 0 does not raise an error but produces NaN (Not a Number). In this case the check leaves the average at the safe starting value 0.0.

Cost: the loop does one addition per element; for n elements, n additions, that is O(n) time. Only two variables are used as extra memory; this means O(1) extra space.

10.5.2Minimum and maximum

To find the smallest and largest elements, two candidate variables are kept. Each element is compared with the candidate; if the candidate is beaten, the element takes its place. The starting value of the candidates is the most critical point of this method:

public class MinMax {
    public static void main(String[] args) {
        int[] nums = {5, 3, 9, 1};
        int min = nums[0], max = nums[0];
        for (int value : nums) {
            if (value < min) min = value;
            if (value > max) max = value;
        }
        System.out.println(min + " " + max);
    }
}
1 9
Table 10.9: The trace table of the MinMax program. Values that change are shown in bold.
Iterationvaluevalue < minvalue > maxminmax
Start———55
155 < 5 → false5 > 5 → false55
233 < 5 → true3 > 5 → false35
399 < 3 → false9 > 5 → true39
411 < 3 → true1 > 9 → false19

The candidates are initialized with the first element of the array. A candidate is always a value that is really in the array, so the result is also an element of the array. Initializing a candidate with 0 looks tempting but is wrong. In an array whose elements are all positive, min is never updated and 0, which is not in the array, is found. In an array whose elements are all negative, the same problem appears with max.

Example 10.2

A method that finds the largest value starts its candidate at 0 and is called with the array {-8, -3, -5}. What is returned?

The candidate is 0. The tests −8 > 0, −3 > 0 and −5 > 0 are made in turn; all three are false. The candidate never changes and the method returns 0. The program run on JDK 21 also prints 0. The correct result is −3, and it is found when the candidate is started with arr[0].

Another point worth noting in the program: the loop also examines the first element, although the candidates already started with that element. The comparisons in the first iteration (5 < 5, 5 > 5) come out false and do no harm. If you like, you can write the loop as a classic for starting at i = 1; the result does not change.

Common mistake

Accessing the first element of an empty array. int min = nums[0]; finds no cell in an array of length 0:

0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
	at EmptyArray.main(EmptyArray.java:5)

The message says “index 0 is outside the bounds of an array of length 0”. In real programs the case nums.length == 0 is handled separately first.

10.5.3Reversing an array

The easy way to reverse an array is to create a new array and copy the elements into it from the end to the start. This way needs n cells of extra memory. A more economical way is to reverse the array in place: the elements at the two ends swap places, and then the ends move one step inward. Because two indices are used, the method is called the two-pointer technique.

import java.util.Arrays;

public class Reverse {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int left = 0, right = arr.length - 1;
        while (left < right) {
            int tmp = arr[left];
            arr[left] = arr[right];
            arr[right] = tmp;
            left++;
            right--;
        }
        System.out.println(Arrays.toString(arr));
    }
}
[5, 4, 3, 2, 1]

The swap is done with three assignments. If arr[left] = arr[right] were written directly, the value on the left would be lost; so it is first saved in the variable tmp. Then the value on the right is written to the left, and the saved value to the right.

Table 10.10: The trace table of the Reverse program.
Stepleftrightleft < righttmparr
Start04——[1, 2, 3, 4, 5]
1st swap04true1[5, 2, 3, 4, 1]
The pointers move13——[5, 2, 3, 4, 1]
2nd swap13true2[5, 4, 3, 2, 1]
The pointers move22false—[5, 4, 3, 2, 1]
0512233441▲ left▲ rightarrtmp1
Figure 10.10: The end of the first swap. The cells left = 0 and right = 4 have swapped: 5 has moved to the front and 1 to the back. tmp still holds 1.

In an array of five elements two swaps are made. In the third iteration both pointers point to cell 2; there is no need to move the middle element, and because 2 < 2 is false, the loop ends. In general, ⌊n/2⌋ swaps are made for an array of n elements; that is O(n) time. The extra memory is only three variables: O(1).

Common mistake

Doing the swap along the whole array. If a[i] and a[a.length - 1 - i] are swapped with for (int i = 0; i < a.length; i++), the swaps done in the first half of the array are undone in the second half. The array {1, 2, 3, 4} ends up as [1, 2, 3, 4] again at the end of the program. The loop must run only up to the middle, with the condition i < a.length / 2.

10.5.4Counting the elements above the average

Some questions cannot be answered in a single pass. “How many students scored above the average?” is one of them. To know whether a grade is above the average, the average is needed first. The average, in turn, can be found only after all the grades have been read. So the array is traversed twice. This is also a valuable property of an array: it stores the data and allows it to be read a second time.

public class AboveAverage {
    public static void main(String[] args) {
        int[] grades = {60, 75, 90, 45, 80};
        int sum = 0;
        for (int x : grades) sum += x;
        double avg = (double) sum / grades.length;
        int above = 0;
        for (int x : grades)
          if (x > avg) above++;
        System.out.println(avg + " " + above);
    }
}
70.0 3
Table 10.11: The trace table of the AboveAverage program. The first pass updates the sum, the second pass the counter.
xPass 1: sumPass 2: x > 70.0above
6060false0
75135true1
90225true2
45270false2
80350true3

At the end of the first pass the sum is 350, and the average is found to be 350 / 5 = 70.0. In the second pass each grade is compared with 70.0; 75, 90 and 80 are above it. The program prints 70.0 3. The total cost of the two passes is 2n comparisons and additions. In big-O notation constant factors are not written; the cost is still O(n).

10.5.5The second largest element

To find the second largest element of an array there is no need to sort it. Two candidates are kept in a single pass: largest and second. Repeated values make the question subtler: in the array {7, 12, 5, 12, 9} the largest is 12 and it occurs twice; the second largest element is 9.

public class SecondLargest {
    public static void main(String[] args) {
        int[] a = {7, 12, 5, 12, 9};
        int largest = Integer.MIN_VALUE;
        int second = Integer.MIN_VALUE;
        for (int x : a) {
          if (x > largest) {
            second = largest;
            largest = x;
          } else if (x > second && x != largest) {
            second = x;
          }
        }
        System.out.println(second);
        System.out.println(Integer.MIN_VALUE);
    }
}
9
-2147483648

Both candidates start at Integer.MIN_VALUE. This constant is the smallest value the int type can take, that is, −2147483648; the second line of the program's output shows it. This way the first element of the array, whatever it is, turns out larger than the candidates. For each element there are two cases:

  1. If x > largest, a new largest has been found. The old largest is not wasted; it drops down to second place: first second = largest, then largest = x. If the order is reversed, the old value is lost.
  2. Otherwise, if x is both greater than second and different from the largest, x is the new second. The condition x != largest prevents a repeat of the largest from being counted as the second.
Table 10.12: The trace table of the SecondLargest program. MIN stands for Integer.MIN_VALUE.
xCaselargestsecond
—StartMINMIN
77 > MIN: new largest7MIN
1212 > 7: new largest, 7 drops to second127
55 is not greater than second (7)127
1212 == largest: a repeat, not counted127
99 > 7 and 9 != 12: new second129

The array is traversed once: O(n) time, O(1) extra space. If the array is empty, has a single element, or all its elements are equal, for example {4, 4}, second is never updated and stays at Integer.MIN_VALUE. If after the loop second is still Integer.MIN_VALUE, there is no second distinct value in the array; in a real program this case should be reported separately as “no second largest”.

10.5.6Counting frequencies: a dice histogram

To count how many times each of the six faces of a die comes up, six counters are needed. Instead of six separate variables and a long if-else chain, a single array of counters is used. The trick of the method is to use the value as the index: if the die shows 3, count[3] is increased by one.

public class Histogram {
    public static void main(String[] args) {
        int[] rolls = {3, 6, 3, 1, 6, 3};
        int[] count = new int[7];
        for (int die : rolls)
          count[die]++;
        for (int y = 1; y <= 6; y++) {
          System.out.print(y + ": ");
          for (int k = 0; k < count[y]; k++)
            System.out.print("*");
          System.out.println();
        }
    }
}
1: *
2: 
3: ***
4: 
5: 
6: **

The counter array has 7 cells, because the die values are between 1 and 6 and cell number 6 is needed. Cell 0 is never used. One cell is wasted, but in return the notation count[die] reads directly. In the example the rolls are given as constants; in a real program they would be generated with random.nextInt(6) + 1.

The first loop counts the rolls. count[die]++ is a single statement: first the value of die is read, the cell with that number is found and the value in the cell is increased by one. After the six rolls the counter array is [0, 1, 0, 3, 0, 0, 2]. The second loop prints one line for each face; the inner loop puts as many stars on that line as the count. Since 2, 4 and 5 never came up, those lines have no stars.

rolls36316300112033405062count
Figure 10.11: The counter array after all the rolls have been counted. The cell number is the die value; cell 0 is drawn faintly because it is not used. The bars above the cells are proportional to the counter values.

The counting loop does a single increment per roll; for m rolls, O(m) time. With an if-else chain, up to six comparisons would be needed for each roll. The same technique is used to find the frequency of letters or exam grades; the only condition is that the values correspond to small non-negative integers.

10.5.7The sieve of Eratosthenes

An old and fast way to find all the prime numbers up to a given number is the sieve of Eratosthenes. The method does not search for primes; it eliminates the non-primes. It starts at 2. Every number that has not been eliminated is prime, and its multiples are eliminated. A boolean array is used to keep track of the eliminated numbers: if composite[k] is true, k has been eliminated.

public class Sieve {
    public static void main(String[] args) {
        int n = 20;
        boolean[] composite = new boolean[n + 1];
        for (int i = 2; i * i <= n; i++)
          if (!composite[i])
            for (int k = i * i; k <= n; k += i)
              composite[k] = true;
        for (int i = 2; i <= n; i++)
          if (!composite[i]) System.out.print(i + " ");
        System.out.println();
    }
}
2 3 5 7 11 13 17 19 

The array has n + 1 cells, because 20 is also used as an index. At the start all the cells are false; this is the default value of a boolean array and means “not yet eliminated”. The inner loop marks the multiples. The steps of the elimination were also traced on JDK 21, and the cells marked for each i are given in Table 10.13.

Table 10.13: The steps of the elimination for n = 20. The word “already” shows that the cell had earlier been marked as a multiple of another prime.
ii * i <= 20CaseValues of k marked
24 <= 20 → trueNot eliminated, prime4, 6, 8, 10, 12, 14, 16, 18, 20
39 <= 20 → trueNot eliminated, prime9, 12 (already), 15, 18 (already)
416 <= 20 → trueEliminated; its multiples are not examined—
525 <= 20 → falseThe outer loop ends—
012✓3✓45✓67✓891011✓1213✓14151617✓1819✓20those with composite[i] = true are crossed out
Figure 10.12: The composite array at the end of the elimination. The crossed-out numbers have been eliminated. The eight numbers with a check mark (2, 3, 5, 7, 11, 13, 17, 19) are prime.

The method has two speed-ups. The first is that multiples start at i * i. Smaller multiples of 3, such as 6, have already been eliminated as multiples of a smaller prime (2). The second is that the outer loop stops with the condition i * i <= n. Every non-prime number up to 20 has a divisor less than or equal to √20 ≈ 4.47. So there is no need to eliminate for 5 and beyond. When the same program is run with n = 100, it finds 25 primes.

The sieve shows that an array can serve both as data and as a “marking board”. Testing whether each number is prime by trial division is much slower than the sieve for large n. The time cost of the sieve is O(n log log n), which in practice grows very close to n. The price is a boolean array of n + 1 cells.

10.6Copying, the Arrays class and methods

The fact that an array variable holds a reference matters most when copying. For a primitive type, int y = x; copies the value and the two variables become independent. For arrays, the same notation gives a completely different result.

10.6.1Reference copy and element copy

The statement int[] b = a; does not create a new array. The reference in a is copied into b; now two variables point to the same object. This situation is called a reference copy. A change made through one is seen through the other, because there is only one array.

StackHeapabc011223011223b = a → the same objectc = a.clone() → a new object
Figure 10.13: Reference copy and element copy. After b = a two arrows point to the same object. c = a.clone(), on the other hand, creates a new array on the heap and copies the elements into it.

For an independent copy, the elements of the array must be transferred to a new array. Java offers three ready-made ways to do this:

  • a.clone(): creates a new array of the same length and copies all the elements.
  • Arrays.copyOf(a, a.length): does the same job; the second argument can also choose the length of the new array.
  • System.arraycopy(src, srcPos, dest, destPos, length): copies a given number of elements, starting from a given position, into an existing destination array.

The third way is the most flexible, but it requires the destination array to be created beforehand:

import java.util.Arrays;

public class ArrayCopy {
    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5};
        int[] d = new int[7];
        System.arraycopy(a, 1, d, 2, 3);
        System.out.println(Arrays.toString(d));
    }
}
[0, 0, 2, 3, 4, 0, 0]

The call System.arraycopy(a, 1, d, 2, 3) means “write 3 elements, starting at cell 1 of a, starting at cell 2 of d”. The elements copied are 2, 3 and 4; they are written into cells 2, 3 and 4 of d. The remaining cells stay at the default value 0.

Definition 10.4

A shallow copy is a copy in which only the values in the cells of an array are copied. If the cells hold primitive values, a shallow copy is completely independent. If the cells hold references, only the references are copied; the objects they point to are shared between the two arrays.

clone, Arrays.copyOf and System.arraycopy make shallow copies. In int arrays this causes no problem, because the cells hold the numbers themselves. In arrays of objects and in two-dimensional arrays, however, the objects are shared, not copied. This trap is treated separately together with two-dimensional arrays.

10.6.2Copying step by step

The program below shows the two kinds of copy side by side. The last line compares two references with ==:

public class Copy {
    public static void main(String[] args) {
        int[] a = {1, 2, 3};
        int[] b = a;
        b[0] = 99;
        System.out.println(a[0]);
        int[] c = a.clone();
        c[1] = 50;
        System.out.println(a[1] + " " + c[1]);
        System.out.println((a == b) + " " + (a == c));
    }
}
99
2 50
true false
Table 10.14: The trace table of the Copy program. “Object 1” and “object 2” are two separate arrays on the heap.
LineabcObject 1Object 2Output
int[] a = {1, 2, 3};→ 1——[1, 2, 3]—
int[] b = a;→ 1→ 1—[1, 2, 3]—
b[0] = 99;→ 1→ 1—[99, 2, 3]—
println(a[0])→ 1→ 1—[99, 2, 3]—99
int[] c = a.clone();→ 1→ 1→ 2[99, 2, 3][99, 2, 3]
c[1] = 50;→ 1→ 1→ 2[99, 2, 3][99, 50, 3]
println(a[1] + " " + c[1])→ 1→ 1→ 2[99, 2, 3][99, 50, 3]2 50
Stack (variables)Heap (objects)011223ab
Stack (variables)Heap (objects)09912230991223copyabc
Figure 10.14: Top: after b = a, two arrows point to the same object. Bottom: after a.clone(), c points to a new object that is a copy of the current contents (99, 2, 3).

The line b[0] = 99 seems to change only b. But the object b points to is also the object of a, and a[0] becomes 99. The clone call, on the other hand, copies the current contents into a new object. After that, a change made through c does not affect a. The output true false on the last line summarizes the two relationships. a == b is true, because the two variables hold the same reference. a == c is false; even though their contents are the same, they are different objects.

10.6.3Arrays helpers

The java.util.Arrays class contains ready-made methods for frequent jobs with arrays. These methods are static and are called with the class name: Arrays.toString(a). The line import java.util.Arrays; is added at the top of the program. The program below runs every row of the table in the slides on JDK 21:

import java.util.Arrays;

public class Helpers {
    public static void main(String[] args) {
        int[] a = {5, 2, 9}, r = {10, 20, 30, 40, 50}, p = {1, 2, 3}, q = {1, 2, 3}, f = new int[4];
        int[][] m = {{1, 2}, {3, 4}};
        System.out.println(Arrays.toString(a));
        System.out.println(Arrays.deepToString(m));
        System.out.println(Arrays.toString(m).startsWith("[[I@"));
        Arrays.fill(f, 7);
        System.out.println(Arrays.toString(f));
        System.out.println((p == q) + " / " + p.equals(q));
        System.out.println(Arrays.equals(p, q));
        System.out.println(Arrays.toString(Arrays.copyOf(a, 5)));
        System.out.println(Arrays.toString(Arrays.copyOf(a, 2)));
        System.out.println(Arrays.toString(Arrays.copyOfRange(r, 1, 4)));
        System.out.println(a);
    }
}
[5, 2, 9]
[[1, 2], [3, 4]]
true
[7, 7, 7, 7]
false / false
true
[5, 2, 9, 0, 0]
[5, 2]
[20, 30, 40]
[I@548c4f57
Table 10.15: Frequently used Arrays methods and their results in the Helpers program.
CallResultExplanation
Arrays.toString(a)[5, 2, 9]Prints the elements of a one-dimensional array
Arrays.deepToString(m)[[1, 2], [3, 4]]Prints nested arrays too, expanding them
Arrays.toString(m)[[I@…For a 2D array, prints the references of the rows
Arrays.fill(f, 7)[7, 7, 7, 7]Writes the same value into all cells
p == q / p.equals(q)false / falseBoth compare references
Arrays.equals(p, q)trueCompares the contents element by element
Arrays.copyOf(a, 5)[5, 2, 9, 0, 0]Longer copy: the extra cells are 0
Arrays.copyOf(a, 2)[5, 2]Shorter copy: truncated at the end
Arrays.copyOfRange(r, 1, 4)[20, 30, 40]Elements 1, 2 and 3; the end index is excluded

The last line of the program shows the result of printing an array directly with println: text that begins with [I@. The leading [I means “int array”. The hexadecimal number after the @ sign is a code belonging to the object, and it can change on every run. This output gives no information about the elements. The same thing happens when Arrays.toString is applied to a two-dimensional array: the cells of the outer array are references to row arrays, and each is printed in the form [I@…. On this line the program only tests that the text begins with [[I@ and prints true; the code itself is not shown because it changes from run to run.

equals needs separate attention. In String, equals compares contents. For arrays, p.equals(q) does the same job as p == q and looks only at the reference. To compare contents, use Arrays.equals(p, q), or Arrays.deepEquals for two-dimensional arrays.

The range in copyOfRange follows a general Java habit: the start index is included and the end index is excluded. copyOfRange(r, 1, 4) takes elements 1, 2 and 3; the length of the copy is 4 − 1 = 3. The same rule holds in the substring method of the String class.

10.6.4Arrays and methods

A method can take an array and return an array. In Java every argument passed to a method is passed by copying. For an array argument, what is copied is the reference, not the array itself. So the parameter in the method points to the same object as the array on the caller's side. Two rules follow:

  1. If the method writes into cells through the parameter, the change is seen in the caller's array too.
  2. If the method assigns a new array to the parameter, only the reference in its own local copy changes; the caller's variable is not affected.
import java.util.Arrays;

public class Methods {
    static void doubleAll(int[] arr) {
        for (int i = 0; i < arr.length; i++)
            arr[i] = arr[i] * 2;
    }

    static void assignNew(int[] arr) {
        arr = new int[]{0, 0, 0};
    }

    static int[] squares(int n) {
        int[] result = new int[n];
        for (int i = 0; i < n; i++)
            result[i] = (i + 1) * (i + 1);
        return result;
    }

    public static void main(String[] args) {
        int[] a = {1, 2, 3};
        doubleAll(a);
        System.out.println(Arrays.toString(a));
        assignNew(a);
        System.out.println(Arrays.toString(a));
        System.out.println(Arrays.toString(squares(4)));
    }
}
[2, 4, 6]
[2, 4, 6]
[1, 4, 9, 16]

In the call doubleAll(a), the parameter arr points to the object of a and writes into its cells; a becomes [2, 4, 6]. assignNew(a), on the other hand, binds a new object to arr. This assignment affects only the method's own variable; a keeps pointing to the old object and stays [2, 4, 6]. The method squares(4) creates a new array and returns its reference. When the method ends, the local variable result disappears, but the array on the heap lives on, because its reference has been given to the caller.

This behavior has a side effect. A method that sorts, reverses or fills an array changes the caller's data permanently. If the original order must be kept, the method should first take a copy. This rule comes up again in the sorting and median examples. Incidentally, the parameter of the main method is also an array: String[] args holds the arguments given on the command line, and args.length gives the number of arguments.

10.7Searching and sorting

The idea, pseudocode and detailed traces of the algorithms linear search, binary search, bubble sort and insertion sort are described in the Algorithms lecture notes. This section focuses on writing the same algorithms with Java arrays, on short traces, and on points specific to arrays: index bounds, in-place changes and the ready-made methods of the Arrays class.

10.7.1Linear search

Linear search traverses the array from start to end and compares each element with the target. At the first match it returns the index; if the target is absent it returns −1. Since −1 cannot be a valid index, it is used to mean “not found”.

public class Linear {
    static int search(int[] arr, int target) {
        for (int i = 0; i < arr.length; i++)
            if (arr[i] == target) return i;
        return -1;
    }

    public static void main(String[] args) {
        int[] d = {8, 3, 6, 2};
        System.out.println(search(d, 6));
        System.out.println(search(d, 5));
    }
}
2
-1
Table 10.16: The trace of the call search(d, 6).
iarr[i]== 6 ?
08false
13false
26true → return 2

Two points stand out in the Java version. First, return i is inside the loop; the method ends at the first match and the remaining elements are not looked at. return -1 is outside the loop and runs only after all the elements have been tried. Putting this line inside the loop by mistake, in an else branch, would end the search at the first element. Second, the arr parameter points to the same array as d; no element is copied during the call. Since 5 is not in the array, the second call returns −1 after four comparisons. In the worst case n comparisons are made: O(n).

10.7.2Arrays.sort and Arrays.binarySearch

Java provides ready-made methods for sorting and binary search. Arrays.sort(a) sorts the array from smallest to largest. Arrays.binarySearch(a, x) searches a sorted array for x using binary search.

import java.util.Arrays;

public class SortDemo {
    public static void main(String[] args) {
        int[] a = {5, 2, 9, 1, 7};
        Arrays.sort(a);
        System.out.println(Arrays.toString(a));
        System.out.println(Arrays.binarySearch(a, 7));
        System.out.println(Arrays.binarySearch(a, 6));
    }
}
[1, 2, 5, 7, 9]
3
-4
before52917Arrays.sort(a)after (sorted in place)0112253749Arrays.binarySearch(a, 7) → 3
Figure 10.15: Arrays.sort sorts the array in place: the cells of the same object are rearranged. In the sorted array the index of 7 is 3.

Arrays.sort does not return a new array; it changes the array itself in place (Figure 10.15). The original order is lost. If the original order is needed for another job, a copy is taken first and the copy is sorted.

If Arrays.binarySearch finds the target, it returns its index. If it does not, it returns a negative value: -(insertion point) - 1. The insertion point is the position at which the target would go in the sorted array. In the sorted array [1, 2, 5, 7, 9], 6 would go between 5 and 7, that is, at position 3. The returned value is −3 − 1 = −4. The “− 1” in the formula makes the result negative even when the insertion point is 0; otherwise −0 and 0 could not be told apart.

Common mistake

Calling Arrays.binarySearch on an unsorted array. The method assumes the array is sorted and does not check it. The result can be meaningless: even for a value that is in the array, the answer may be “not present”. A question in the Test Yourself section shows this on a concrete array.

Both methods are in the java.util.Arrays class and require import java.util.Arrays;. For arrays of primitive types, Arrays.sort uses a kind of quicksort that runs in O(n log n) time on average. For large arrays this is much better than the O(n²) cost of bubble sort and insertion sort.

10.7.3The median

Definition 10.5

The median is the value exactly in the middle of a sorted array. If the number of elements n is odd, the median is s[n / 2]. If n is even, it is the average of the two middle elements, s[n/2 − 1] and s[n/2].

An advantage of the median over the average is that it is not affected by extreme values. The average of the array {1, 2, 3, 4, 100} is 110 / 5 = 22.0; this value is close to none of the elements. The median is 3. In data such as income, house prices or response times there are a few extreme values, so the median gives a more meaningful “typical value”.

import java.util.Arrays;

public class Median {
    public static void main(String[] args) {
        int[] a = {7, 3, 9, 1, 5};
        int[] s = Arrays.copyOf(a, a.length);
        Arrays.sort(s);    // a is untouched
        int n = s.length;
        double m = (n % 2 == 1) ? s[n / 2]
            : (s[n/2 - 1] + (double) s[n/2]) / 2;
        System.out.println(m);   // 5.0
        System.out.println(Arrays.toString(a) + " " + Arrays.toString(s));
    }
}
5.0
[7, 3, 9, 1, 5] [1, 3, 5, 7, 9]
odd number of elements (n = 5), sorted0113253749s[n / 2] = s[2] → 5even number of elements (n = 4), sorted02132638(s[1] + s[2]) / 2.0 → 4.5
Figure 10.16: Top: an odd number of elements (n = 5): the median is s[2] = 5. Bottom: an even number of elements (n = 4): the median is (s[1] + s[2]) / 2.0 = (3 + 6) / 2.0 = 4.5.

The program has three points specific to arrays. First, the sorting is done on a copy: s is created with Arrays.copyOf and the original order of a is preserved. The second line of the program's output confirms this: a is still [7, 3, 9, 1, 5]. Second, the conditional operator (? :) combines the odd and even cases in a single expression. Third, in the even case s[n/2] is cast with (double) before the addition. This way both the addition and the division are done in double: the sum of two large ints cannot overflow the int limit, and the quotient comes out fractional. Without the cast, the quotient of two ints would be taken, and (3 + 6) / 2 would give 4 instead of 4.5. The program below verifies this difference and the extreme-value example on JDK 21:

import java.util.Arrays;

public class Median2 {
    static double median(int[] a) {
        int[] s = Arrays.copyOf(a, a.length);
        Arrays.sort(s);
        int n = s.length;
        return (n % 2 == 1) ? s[n / 2] : (s[n/2 - 1] + (double) s[n/2]) / 2;
    }

    public static void main(String[] args) {
        int[] u = {1, 2, 3, 4, 100};
        int t = 0;
        for (int x : u) t += x;
        System.out.println((double) t / u.length + " " + median(u));
        System.out.println(median(new int[]{8, 2, 6, 3}));
        System.out.println((3 + 6) / 2);
    }
}
22.0 3.0
4.5
4

The sorting determines the cost: O(n log n). The copy needs n cells of extra memory. There are also methods that find the median without sorting, in O(n) time on average, but they are outside the scope of this course.

Common mistake

A method that finds the median but sorts the array without copying it. Because the reference to the array is passed to the method, Arrays.sort(arr) sorts the caller's array too. After getting the median, the caller finds that the order of its own array has changed. The fix is to sort a copy taken inside the method with arr.clone() or Arrays.copyOf.

10.7.4Bubble sort

Bubble sort compares neighboring elements and swaps those that are out of order. On each pass the largest of the remaining elements settles at the end, like a bubble rising to the surface of water. The Java version is two nested for loops:

import java.util.Arrays;

public class Bubble {
    public static void main(String[] args) {
        int[] a = {5, 1, 4, 2};
        int n = a.length;
        for (int pass = 0; pass < n - 1; pass++) {
          for (int j = 0; j < n - 1 - pass; j++) {
            if (a[j] > a[j + 1]) {
              int tmp = a[j];
              a[j] = a[j + 1];
              a[j + 1] = tmp;
            }
          }
        }
        System.out.println(Arrays.toString(a));
    }
}
[1, 2, 4, 5]

The outer loop counts the passes: n − 1 passes are enough for n elements, because once n − 1 elements are in place the last one is automatically in place. The bound of the inner loop is j < n - 1 - pass. This bound has two array-specific details. The first is the “- 1”: since the body accesses a[j + 1], j can be at most n − 2. If the bound were j < n, a[n] would be read on the last iteration and an out-of-bounds error would result. The second is the “- pass”: since each pass puts one element at the end in its place, there is no need to look at that region again.

Table 10.17: The passes of bubble sort on the array {5, 1, 4, 2}. The values come from the JDK 21 output of a version with a counter added.
PassSteps in the inner loopArray at the end of the passComparisonsSwaps
15↔1, 5↔4, 5↔2[1, 4, 2, 5]33
21–4 in order, 4↔2[1, 2, 4, 5]21
31–2 in order[1, 2, 4, 5]10

The total number of comparisons is 3 + 2 + 1 = 6. In general, for n elements (n − 1) + (n − 2) + … + 1 = n(n − 1)/2 comparisons are made; this is O(n²). In the third pass there is no swap at all, because the array was already sorted after the second pass. This observation leads to an improvement: if no swap is made in a pass, the loop can stop early. This improvement is one of the exercises in the slides. The sort is done in place; the extra memory is only the variable tmp: O(1).

10.7.5Insertion sort

Insertion sort grows a sorted part on the left of the array. On each iteration the element immediately to the right of the sorted part is taken as the key. The elements in the sorted part that are larger than the key are shifted one cell to the right, and the key is written into the gap that opens up. It resembles arranging playing cards in your hand.

import java.util.Arrays;

public class Insertion {
    public static void main(String[] args) {
        int[] a = {4, 3, 5, 1};
        for (int i = 1; i < a.length; i++) {
          int key = a[i];
          int j = i - 1;
          while (j >= 0 && a[j] > key) {
            a[j + 1] = a[j];
            j--;
          }
          a[j + 1] = key;
        }
        System.out.println(Arrays.toString(a));
    }
}
[1, 3, 4, 5]
Table 10.18: The iterations of insertion sort on the array {4, 3, 5, 1}.
ikeyElements shifted rightIndex where the key is writtenArray at the end of the iteration
1340[3, 4, 5, 1]
25—2[3, 4, 5, 1]
315, 4, 30[1, 3, 4, 5]

The code has three points specific to arrays. First, the key is saved in a separate variable with int key = a[i];. This is necessary because the shifting will overwrite a[i]. The intermediate steps of the third iteration show this clearly. During the shifts the array goes through the states [3, 4, 5, 5], [3, 4, 4, 5] and [3, 3, 4, 5]. During this time the value 1 lives only in key. Second, the check j >= 0 in the while condition comes first. The && operator is evaluated from left to right and does not look at the right side if the left side is false. When j is −1, a[j] is not read and an out-of-bounds error is avoided. If the order of the conditions were reversed (a[j] > key && j >= 0), the program would stop at a[-1] whenever the key is the smallest in the array. Third, when the loop ends, the key is written to a[j + 1], because j stops one place to the left of the last element shifted.

In the worst case, when the array is in reverse order, every key shifts the whole sorted part and the cost is O(n²). If the array is already almost sorted, there is very little shifting and the cost approaches O(n). This is why insertion sort is a good choice for small or nearly sorted arrays.

10.7.6Binary search

Binary search works only on a sorted array. It looks at the element in the middle of the search range. If the target is larger than the middle element, the left half is eliminated; if smaller, the right half is. Because the range is halved at every step, an array of n elements needs at most about log₂ n + 1 iterations. In the Java version the range is kept with two indices: lo (lower bound) and hi (upper bound).

public class Binary {
    public static void main(String[] args) {
        int[] a = {2, 5, 8, 12, 16, 23, 38, 56};
        int target = 23, lo = 0, hi = a.length - 1;
        int result = -1;
        while (lo <= hi) {
          int mid = lo + (hi - lo) / 2;
          if (a[mid] == target) { result = mid; break; }
          if (a[mid] < target) lo = mid + 1;
          else hi = mid - 1;
        }
        System.out.println(result);
    }
}
5
Table 10.19: Searching for 23 in the array {2, 5, 8, 12, 16, 23, 38, 56}.
Iterationlohimida[mid]Decision
10731212 < 23 → lo = 4
247523found: result = 5

23 is found in two iterations. Linear search would make six comparisons for the same target. In a small array the difference looks slight. In a sorted array of a million elements, however, binary search needs at most 20 iterations, while linear search on the same array may make up to a million comparisons.

The array-specific points are these. Initially hi = a.length - 1; a.length is not a valid index. The loop condition is lo <= hi: when lo and hi are equal, there is still one element in the range and it must be examined. mid = lo + (hi - lo) / 2 is integer division and rounds down: 0 + (7 − 0) / 2 = 3. This form gives the same result as (lo + hi) / 2, but for very large indices it prevents the sum lo + hi from overflowing (Chapter 4.1). Finally, the ±1 in the updates lo = mid + 1 and hi = mid - 1 is essential. mid has already been examined. If the update is written as lo = mid, the range may fail to shrink in some cases and the loop runs forever.

10.7.7Unsuccessful binary search

If the target is not in the array, the range eventually becomes empty: lo passes hi. At that moment lo shows the position where the target would go in the sorted array, that is, the insertion point. The method below returns this information by the same rule as Arrays.binarySearch:

import java.util.Arrays;

public class BinaryMiss {
    static int search(int[] a, int x) {
      int lo = 0, hi = a.length - 1;
      while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;
        if (a[mid] == x) return mid;
        if (a[mid] < x) lo = mid + 1; else hi = mid - 1;
      }
      return -(lo + 1);
    }

    public static void main(String[] args) {
        System.out.println(search(new int[]{2, 4, 6, 8}, 5));
        System.out.println(Arrays.binarySearch(new int[]{2, 4, 6, 8}, 5));
        System.out.println(search(new int[]{2, 4, 6, 8}, 1) + " " + search(new int[]{2, 4, 6, 8}, 9));
    }
}
-3
-3
-1 -5
Table 10.20: Searching for 5 in the array {2, 4, 6, 8}.
Iterationlohimida[mid]Decision
103144 < 5 → lo = 2
223266 > 5 → hi = 1
—21lo > hi: the loop ends

When the loop ends, lo = 2 and the method returns −(2 + 1) = −3. The second line of the program shows that Arrays.binarySearch also returns −3 for the same array and the same target. A negative result means “not present”. The insertion point is recovered from the result: −(−3) − 1 = 2. Indeed, 5 would go between 4 and 6, at position 2. The third line tests two edge cases. For 1, which is smaller than the smallest element, the insertion point is 0 and the return value is −1. For 9, which is larger than the largest, the insertion point is 4 and the return value is −5.

10.7.8Basic complexities

The costs of the array operations seen in these notes follow directly from the structure of the array. Table 10.21 gives them together.

Table 10.21: Time complexities of basic array operations (n: number of elements).
OperationTimeReason
Access by indexO(1)The address is computed with a single multiplication and addition
Linear searchO(n)In the worst case every element is examined
Full traversalO(n)Each element is visited once
Insert / delete in the middleO(n)The following elements are shifted one cell
Binary search (sorted array)O(log n)The range is halved at every step
Two nested full traversalsO(n²)For each element the whole array is examined
To insert 4 at position 1, the elements on the right shift:031825364after:0314283546shift count ≈ n → O(n)
Figure 10.17: To insert 4 at position 1, 8, 5 and 6 each shift one cell to the right. The number of shifts is proportional to the number of elements: O(n).

Figure 10.17 makes the cost of inserting in the middle concrete. It is assumed that there is a free cell at the end of the array. Every element after the insertion point moves one place to the right; the shifting is done from right to left, otherwise the elements overwrite one another. Bubble sort and insertion sort use two nested loops, so they fall in the O(n²) row. Arrays.sort, with its O(n log n) cost, sits between these rows.

10.8Two-dimensional arrays

The grades of the students in a class on three exams, the pixel colors of a picture, or the squares of a game board are arranged in rows and columns. For this kind of data, a structure with two indices is more natural: one selects the row and the other the column.

10.8.1Declaring a matrix and accessing it

Definition 10.6

A two-dimensional array is an array whose elements are accessed with two indices. This structure of rows and columns is also called a matrix. In Java, a two-dimensional array is an array of arrays: each cell of the outer array holds the reference to a row array.

The type is written int[][]. In an initializer, each row is given in its own curly braces. An empty matrix is created with new int[2][3]: 2 rows, 3 columns in each row, all cells 0.

public class Matrix {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6}
        };
        int value = matrix[1][2]; // 6
        System.out.println(value + " " + matrix.length + " " + matrix[0].length);
        int[][] empty = new int[2][3];
        System.out.println(empty[1][2]);
    }
}
6 2 3
0

In an access, the first index selects the row and the second the column. matrix[1][2] is column 2 of row 1, that is, 6. The reading goes from left to right: first matrix[1] finds the row array, then the cell numbered 2 of that array is reached.

StackHeapmatrixrows00112231041526matrix[1][2] → 6
Figure 10.18: int[][] matrix = {{1, 2, 3}, {4, 5, 6}}; in memory. The variable matrix points to the outer array of two cells. Each cell of the outer array points to a row array of three cells. The highlighted cell is matrix[1][2] = 6.

Figure 10.18 shows what the “array of arrays” idea looks like in memory. Two important consequences follow from this structure:

  • matrix.length is the length of the outer array, that is, the number of rows (2). matrix[0].length is the length of row 0, that is, the number of columns in that row (3).
  • matrix[1] on its own is a valid expression and is an int[], a whole row. Arrays.toString(matrix[1]) prints that row as [4, 5, 6].

10.8.2Jagged arrays

Because the rows are separate objects, they do not all have to be the same length. A two-dimensional array whose rows have different lengths is called a jagged array. To create one, only the number of rows is given in the new expression; the rows are created one by one afterward:

public class Jagged {
    public static void main(String[] args) {
        int[][] m = new int[3][];
        m[0] = new int[1];
        m[1] = new int[2];
        m[2] = new int[3];
        for (int i = 0; i < m.length; i++)
            System.out.print(m[i].length + " ");
        System.out.println();
    }
}
1 2 3 
Table 10.22: The trace table of the Jagged program.
Linem[0]m[1]m[2]Output
m = new int[3][];nullnullnull
m[0] = new int[1];[0]nullnull
m[1] = new int[2];[0][0, 0]null
m[2] = new int[3];[0][0, 0][0, 0, 0]
loop, i = 0, 1, 2samesamesame1 2 3
StackHeapmouter array001002000
Figure 10.19: The jagged array after all three rows have been created. The cells of the outer array point to three separate row objects of lengths 1, 2 and 3.

new int[3][] creates only the outer array. Because the cells of the outer array hold references, their default values are null. If an expression such as m[1].length is run before the rows have been assigned, the program stops with a NullPointerException. The message from JDK 21 is:

> java JaggedNull
6
Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because "<local1>[1]" is null
	at JaggedNull.main(JaggedNull.java:7)

The message says “the array length cannot be read because <local1>[1] is null”. <local1> is the name of the variable m in the compiled code. If the source is compiled with the javac -g option, the message shows the real name of the variable:

> javac -g JaggedNull.java
> java JaggedNull
6
Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because "m[1]" is null
	at JaggedNull.main(JaggedNull.java:7)

Jagged arrays save memory for triangular data: Pascal's triangle, or half of a distance table.

10.8.3The shallow-copy trap

In a two-dimensional array, clone copies only the outer array. The cells of the outer array hold the references of the rows, and it is these references that are copied. As a result, two separate outer arrays point to the same row objects.

import java.util.Arrays;

public class Shallow {
    public static void main(String[] args) {
        int[][] a = {{1, 2}, {3, 4}};
        int[][] b = a.clone();
        b[0][0] = 99;
        b[1] = new int[]{7, 8};
        System.out.println(Arrays.deepToString(a));
        System.out.println(Arrays.deepToString(b));
    }
}
[[99, 2], [3, 4]]
[[99, 2], [7, 8]]
Table 10.23: The trace table of the Shallow program. Row 1 and row 2 are the two initial row objects; row 3 is created later.
LineabEffect
int[][] a = {{1, 2}, {3, 4}};[row 1, row 2]—Row 1 = [1, 2], row 2 = [3, 4]
int[][] b = a.clone();[row 1, row 2][row 1, row 2]New outer array, rows shared
b[0][0] = 99;samesameRow 1 = [99, 2]; a[0][0] is also 99
b[1] = new int[]{7, 8};[row 1, row 2][row 1, row 3]Only the cell of b changes
StackHeapa99234b78new rowa[0] = b[0] (shared)
Figure 10.20: Memory after a new row is bound to b[1]. a[0] and b[0] point to the same row (99, 2). a[1] remains on the old row (3, 4), while b[1] points to the new row (7, 8).

The two lines giving different results are the heart of the trap. b[0][0] = 99 writes into the shared row object, so it is seen from a too. b[1] = new int[]{7, 8}, on the other hand, writes not inside a row but into the cell of the outer array of b. That cell belongs only to b and a is not affected. For a true, that is deep, copy, each row is copied separately:

import java.util.Arrays;

public class Deep {
    public static void main(String[] args) {
        int[][] a = {{1, 2}, {3, 4}};
        int[][] b = new int[a.length][];
        for (int i = 0; i < a.length; i++)
            b[i] = a[i].clone();
        b[0][0] = 99;
        System.out.println(Arrays.deepToString(a));
        System.out.println(Arrays.deepToString(b));
    }
}
[[1, 2], [3, 4]]
[[99, 2], [3, 4]]

This time b[0][0] = 99 changes only the row that belongs to b; a stays [[1, 2], [3, 4]]. The b[i] = a[i].clone() in the loop creates a separate object for each row.

10.8.4Traversing a matrix row by row

To traverse all the cells of a matrix, two nested loops are used. The outer loop goes through the rows, and the inner loop goes through the columns of that row:

public class Traverse {
    public static void main(String[] args) {
        int[][] matrix = {{1, 2, 3}, {4, 5, 6}};
        for (int i = 0; i < matrix.length; i++) {
          for (int j = 0; j < matrix[i].length; j++) {
            System.out.print(matrix[i][j] + " ");
          }
          System.out.println();
        }
    }
}
1 2 3 
4 5 6 

The bound of the inner loop is matrix[i].length; that is, each row is traversed up to its own length. This form also works correctly for jagged arrays. The cells are printed on the same line with print, separated by spaces. When a row is finished, the inner loop is left and println() moves to the next line.

Table 10.24: The order in which cells are visited in the Traverse program.
Stepijmatrix[i][j]Line on the console
10011
20121 2
30231 2 3 ⏎
41044
51154 5
61264 5 6 ⏎
00112231456i ↓ j →
Figure 10.21: A 2 × 3 matrix. i selects the row going down and j the column going right. In row-by-row traversal, the three cells of row 0 are visited first, then the three cells of row 1.

In total 2 × 3 = 6 cells are traversed. In general, for a matrix with r rows and c columns, the cost is O(r · c). For a square n × n matrix this is O(n²). Operations such as a row sum, a column sum or finding the largest cell are all built on this skeleton. For the sum of each row, for example, int sum = 0; is written before the inner loop and the sum is printed when the inner loop ends.

10.8.5Matrix transpose

The transpose of a matrix is the matrix in which rows become columns and columns become rows. The transpose of an r × c matrix is c × r, and it is filled by the rule t[j][i] = matrix[i][j].

import java.util.Arrays;

public class Transpose {
    public static void main(String[] args) {
        int[][] matrix = {{1, 2, 3}, {4, 5, 6}};
        int rows = matrix.length;
        int cols = matrix[0].length;
        int[][] t = new int[cols][rows];
        for (int i = 0; i < rows; i++)
            for (int j = 0; j < cols; j++)
                t[j][i] = matrix[i][j];
        System.out.println(Arrays.deepToString(t));
    }
}
[[1, 4], [2, 5], [3, 6]]
Table 10.25: The trace table of the Transpose program.
ijAssignmentt (at the end of the step)
00t[0][0] = matrix[0][0] = 1[[1, 0], [0, 0], [0, 0]]
01t[1][0] = matrix[0][1] = 2[[1, 0], [2, 0], [0, 0]]
02t[2][0] = matrix[0][2] = 3[[1, 0], [2, 0], [3, 0]]
10t[0][1] = matrix[1][0] = 4[[1, 4], [2, 0], [3, 0]]
11t[1][1] = matrix[1][1] = 5[[1, 4], [2, 5], [3, 0]]
12t[2][1] = matrix[1][2] = 6[[1, 4], [2, 5], [3, 6]]
00112231456matrix (2×3)00114125236t (3×2)
Figure 10.22: The 2 × 3 matrix and its 3 × 2 transpose t. Row 0 of the matrix (1, 2, 3) has become column 0 of t.

In the code the dimensions are read first: rows = matrix.length (2) and cols = matrix[0].length (3). The target array is created with the dimensions swapped: new int[cols][rows], that is, 3 × 2. Taking the number of columns from matrix[0].length assumes that all the rows are the same length; the transpose is meaningful only for regular matrices anyway. Each cell is copied once: O(r · c) time, and r · c cells of extra memory for the target matrix.

10.8.6Matrix multiplication

The product of two matrices C = A × B is defined as follows: the cell of C in row i and column j is the sum of the products of the corresponding elements of row i of A and column j of B. The number of columns of A must equal the number of rows of B.

C[i][j] = A[i][0] · B[0][j] + A[i][1] · B[1][j] + … + A[i][m−1] · B[m−1][j]

import java.util.Arrays;

public class MatMul {
    public static void main(String[] args) {
        int[][] A = {{1, 2}, {3, 4}};
        int[][] B = {{5, 6}, {7, 8}};
        int[][] C = new int[2][2];
        for (int i = 0; i < 2; i++)
          for (int j = 0; j < 2; j++)
            for (int k = 0; k < 2; k++)
              C[i][j] += A[i][k] * B[k][j];
        System.out.println(Arrays.deepToString(C));
    }
}
[[19, 22], [43, 50]]
Example 10.3

For A = [[1, 2], [3, 4]] and B = [[5, 6], [7, 8]], let us compute the four cells of C step by step. Each cell is the sum of two products, because A has 2 columns.

  • C[0][0] = A[0][0] · B[0][0] + A[0][1] · B[1][0] = 1 · 5 + 2 · 7 = 5 + 14 = 19
  • C[0][1] = A[0][0] · B[0][1] + A[0][1] · B[1][1] = 1 · 6 + 2 · 8 = 6 + 16 = 22
  • C[1][0] = A[1][0] · B[0][0] + A[1][1] · B[1][0] = 3 · 5 + 4 · 7 = 15 + 28 = 43
  • C[1][1] = A[1][0] · B[0][1] + A[1][1] · B[1][1] = 3 · 6 + 4 · 8 = 18 + 32 = 50

The result is [[19, 22], [43, 50]], the same as the JDK 21 output.

1234A×5678B=19224350CA[1][1] × B[1][1]= 4 × 8 = 32
Figure 10.23: The last step of the last cell: C[1][1] += A[1][1] × B[1][1] = 4 × 8 = 32, so 18 + 32 = 50. Row 1 of A and column 1 of B have been used.

The code has three nested loops. i and j select the cell to be computed; k runs over the terms of the sum. The statement C[i][j] += A[i][k] * B[k][j] adds each term to the cell. Because C was created with new int[2][2], its cells start at 0; there is no need to zero them separately. For square n × n matrices, n multiplications are made for each cell and n³ multiplications for the n² cells in total: O(n³). For 100 × 100 matrices this is a million multiplications.

10.9Array or list?

The length of an array is fixed. If the number of elements grows and shrinks while the program runs, this limit is annoying: with every insertion a new, larger array has to be created and the old elements copied into it. The ArrayList class in Java's collections library does this job by itself.

An array does not grow when full:3856+ 7 ?new, larger array + copying38567ArrayList does this by itself.
Figure 10.24: 7 cannot be added to a full array, because the array does not grow. A new, larger array is created, the elements are copied and 7 is written into an empty cell. ArrayList performs these steps by itself.
import java.util.ArrayList;

public class ListDemo {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(3);
        list.add(8);
        list.add(5);
        list.add(7);
        System.out.println(list + " " + list.size() + " " + list.get(1));
    }
}
[3, 8, 5, 7] 4 8

Internally, ArrayList still uses an array. When the array fills up, it creates a larger one and moves the elements there (Figure 10.24). The programmer only calls methods such as add, get and size. For access, list.get(1) is written instead of square brackets, and list.size() instead of length for the length.

This convenience has a price. An int[] stores the numbers directly in its cells. An ArrayList<Integer>, however, can hold only objects; each number is put inside an Integer object, and the list holds the references to these objects. This means more memory and somewhat slower access. A rough rule for choosing can be given:

  • If the number of elements is known in advance and fixed, for example the days of the week, the cells of a matrix or a table of counters, an array is sufficient and fast.
  • If the number of elements will change while the program runs, for example records entered by the user, a collection such as ArrayList is more convenient.

The final decision is made according to how it will be used, the readability of the code and, if necessary, measured performance. The traversal, search and sorting methods learned in these notes apply to lists in the same way.

10.10Common mistakes

Most mistakes with arrays fall into four groups. This section gives each with an example that was actually run.

i <= a.length → a[5] on the last iteration3081126324✗5a.length = 5 → valid indices 0 … 4int[] b = a; b[0] = 9;ab923one array: a[0] also becomes 9
Figure 10.25: Two common mistakes. Left: one iteration too many, where i <= a.length accesses the nonexistent a[5] on the last iteration. Right: a reference copy, where after b = a, b[0] = 9 changes the single shared array and a[0] becomes 9 too.
Common mistake

One iteration too many. The condition i <= a.length accesses a[length] on the last iteration, and an ArrayIndexOutOfBoundsException is thrown. The correct form is i < a.length. The same mistake has a silent sibling: writing i < a.length - 1 skips the last element and gives no message.

Common mistake

The first element of an empty array. int min = a[0]; stops with the message “Index 0 out of bounds for length 0” on an empty array. Before computing the minimum, the maximum or the median, the case a.length == 0 is handled separately.

Common mistake

A reference copy. int[] b = a; is not a new array; b[0] = 9 changes a too. For an independent copy, use a.clone() or Arrays.copyOf. For two-dimensional arrays these are not enough either; each row is copied separately.

Common mistake

A fixed number of columns in a jagged matrix. Using matrix[0].length for every row in the inner loop assumes that all the rows are as long as the first. In the following program the second row has only one element:

public class JaggedError {
    public static void main(String[] args) {
        int[][] m = {{1, 2, 3}, {4}};
        int sum = 0;
        for (int i = 0; i < m.length; i++)
            for (int j = 0; j < m[0].length; j++)
                sum += m[i][j];
        System.out.println(sum);
    }
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
	at JaggedError.main(JaggedError.java:7)

When i = 1, j becomes 1 and cell number 1 is looked up in a row of length 1. When the inner loop bound is changed to m[i].length, the program prints 10.

What these four mistakes have in common is that the compiler catches none of them. All of them show up either as an exception at run time or as a wrong result with no message at all. So when writing array code, three boundary cases are always tried: an empty array, an array with a single element, and an array in which the target is in the first or last position.

10.11Summary

  • An array is an object that holds a fixed number of elements of the same type in consecutive cells. Indices run from 0 to length − 1; length is a field and does not change after creation.
  • An array variable lives on the stack and holds the reference to the array object on the heap. Cells created with new receive the default value: 0 for numbers, false for boolean and null for objects. The initializer {…} takes the length from the number of values.
  • Reading and writing a[i] are done in O(1) time, because the address is computed with the formula start + i × cell size. An invalid index stops the program with an ArrayIndexOutOfBoundsException; the most common cause is a loop condition written with <=.
  • The classic for is used when an index is needed, and the enhanced for when you only read. The loop variable in the enhanced for is a copy of the element; assigning to it does not change the array.
  • The sum and average are found with an accumulator, and the minimum and maximum with candidates initialized to the first element of the array. Reversing is done in place with two pointers. In frequency counting the value is used as the index. The sieve of Eratosthenes eliminates the non-primes with a boolean array.
  • b = a copies only the reference. clone, Arrays.copyOf and System.arraycopy copy the elements, but make shallow copies. == and equals compare references, while Arrays.equals compares contents. An array passed to a method is the same object as the caller's array.
  • Linear search takes O(n) time, and binary search on a sorted array O(log n). Arrays.sort sorts the array in place; Arrays.binarySearch returns -(insertion point) - 1 if it does not find the target. Bubble sort and insertion sort are O(n²).
  • int[][] is an array of arrays. matrix.length is the number of rows, and matrix[i].length is the number of columns of that row. Rows can have different lengths (a jagged array). clone copies only the outer array. Traversal is done with two nested loops, and matrix multiplication with three.

10.12Key terms

  • array
  • element
  • cell
  • index
  • length
  • reference
  • heap
  • stack
  • default value
  • array initializer
  • null reference
  • out of bounds
  • exception
  • traversal
  • enhanced for loop
  • reversing
  • pointer
  • swap
  • frequency
  • Sieve of Eratosthenes
  • copy
  • shallow copy
  • linear search
  • binary search
  • median
  • bubble sort
  • insertion sort
  • time complexity
  • two-dimensional array
  • multidimensional array
  • matrix
  • jagged array

10.13Test Yourself

  1. What is the output of the following program?

    import java.util.Arrays;
    
    public class TY1 {
        public static void main(String[] args) {
            int[] a = new int[4];
            a[a.length - 1] = a.length;
            a[a[3] - 3] = 9;
            System.out.println(Arrays.toString(a));
        }
    }
    Answer
    [0, 9, 0, 4]

    The array starts with four zeros. a[a.length - 1] = a.length writes 4 into the last cell, a[3]. In the next line the inner expression is computed first: a[3] - 3 = 4 − 3 = 1. So 9 is written into a[1].

  2. In the following program, what is a after the method zeroOut has been called?

    import java.util.Arrays;
    
    public class TY2 {
        static void zeroOut(int[] d) {
            d[0] = 0;
            d = new int[]{5, 5, 5};
            d[1] = 0;
        }
    
        public static void main(String[] args) {
            int[] a = {1, 2, 3};
            zeroOut(a);
            System.out.println(Arrays.toString(a));
        }
    }
    Answer
    [0, 2, 3]

    The reference of a goes to the method. d[0] = 0 writes into the shared array, and a[0] becomes 0. d = new int[]{5, 5, 5}, however, only binds the method's local variable to a new array. The following d[1] = 0 changes this new array; a is not affected.

  3. What is the output of the following program? Why is each of the three values what it is?

    import java.util.Arrays;
    
    public class TY3 {
        public static void main(String[] args) {
            int[] p = {4, 5};
            int[] q = p.clone();
            int[] r = p;
            System.out.println((p == q) + " " + (p == r) + " " + Arrays.equals(p, q));
        }
    }
    Answer
    false true true

    p == q is false, because clone creates a new object. p == r is true, because r = p copies the same reference. Arrays.equals(p, q) is true, because the two arrays have the same length and the same elements.

  4. Arrays.binarySearch looks for 1 first in an unsorted array and then in a sorted one. What is the output, and why is the first result wrong?

    import java.util.Arrays;
    
    public class TY4 {
        public static void main(String[] args) {
            int[] a = {5, 1, 9, 3, 7};
            System.out.println(Arrays.binarySearch(a, 1));
            Arrays.sort(a);
            System.out.println(Arrays.binarySearch(a, 1));
        }
    }
    Answer
    -1
    0

    In the first search the range is 0…4 and the middle element is a[2] = 9. Since 1 < 9, the right half is eliminated. Then a[0] = 5 is looked at; since 1 < 5, the search goes left again and the range becomes empty. The method returns −1, although 1 is in the array, at position 1. Because the method assumes the array is sorted, it has eliminated the wrong half. After sorting, the array is [1, 3, 5, 7, 9] and 1 is correctly found at position 0.

  5. The following program creates a triangular jagged array. What are t[3].length and the total number of cells?

    public class TY5 {
        public static void main(String[] args) {
            int[][] t = new int[4][];
            int cells = 0;
            for (int i = 0; i < t.length; i++) {
                t[i] = new int[i + 1];
                cells += t[i].length;
            }
            System.out.println(t[3].length + " " + cells);
        }
    }
    Answer
    4 10

    Row number i has i + 1 cells: 1, 2, 3 and 4. The length of the last row is 4, and the total number of cells is 1 + 2 + 3 + 4 = 10. A regular 4 × 4 matrix would need 16 cells.

  6. The reverse-sorted array {4, 3, 2, 1} is sorted with bubble sort. How many comparisons and how many swaps are made?

    import java.util.Arrays;
    
    public class TY6 {
        public static void main(String[] args) {
            int[] a = {4, 3, 2, 1};
            int comps = 0, swaps = 0;
            for (int pass = 0; pass < a.length - 1; pass++)
                for (int j = 0; j < a.length - 1 - pass; j++) {
                    comps++;
                    if (a[j] > a[j + 1]) {
                        int tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp;
                        swaps++;
                    }
                }
            System.out.println(Arrays.toString(a) + " " + comps + " " + swaps);
        }
    }
    Answer
    [1, 2, 3, 4] 6 6

    The number of comparisons does not depend on the contents of the array: 3 + 2 + 1 = 6. In a reverse-sorted array, every comparison finds an out-of-order pair and ends in a swap; the number of swaps is also 6. This is the worst case for n = 4: n(n − 1)/2 = 6.

  7. The following program looks for the most frequent digit in an array. What is the output? Why does the counts array have 10 cells?

    public class TY7 {
        public static void main(String[] args) {
            int[] a = {2, 7, 7, 3, 7};
            int[] counts = new int[10];
            for (int x : a) counts[x]++;
            int mostCommon = 0;
            for (int d = 1; d < counts.length; d++)
                if (counts[d] > counts[mostCommon]) mostCommon = d;
            System.out.println(mostCommon + " " + counts[mostCommon]);
        }
    }
    Answer
    7 3

    The values are used as indices: counts[x]++. Because digits are between 0 and 9, 10 cells are needed. At the end of counting, counts[2] = 1, counts[3] = 1 and counts[7] = 3. The second loop looks for the index of the largest counter; since 7 occurs three times, the result is 7 3.

  8. The following program fills a 3 × 3 matrix. What are m[2][1] and m[1][2]?

    public class TY8 {
        public static void main(String[] args) {
            int[][] m = new int[3][3];
            for (int i = 0; i < 3; i++)
                for (int j = 0; j < 3; j++)
                    m[i][j] = i * 3 + j;
            System.out.println(m[2][1] + " " + m[1][2]);
        }
    }
    Answer
    7 5

    Each cell is given i * 3 + j; the cells end up numbered row by row from 0 to 8. m[2][1] = 2 · 3 + 1 = 7 and m[1][2] = 1 · 3 + 2 = 5. Because the first index is the row and the second the column, the two expressions refer to different cells.

  9. To print an array of length n from the end to the start, a programmer writes the loop for (int i = a.length; i >= 0; i--). What error occurs, and how is the loop corrected?

    Answer

    In the first iteration i = a.length, and an attempt is made to read a[a.length]. Run with a three-element array, the program stops without printing anything:

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
    	at TY9.main(TY9.java:5)

    Because the last valid index is a.length - 1, the correct start is int i = a.length - 1. The condition i >= 0 is right, because cell 0 must also be printed.

10.14Further reading

  • Oracle, The Java Tutorials, “Arrays”: explains array declaration, creation, multidimensional arrays, copying and the java.util.Arrays methods with short, runnable examples.
  • R. Sedgewick and K. Wayne, Computer Science: An Interdisciplinary Approach (Addison-Wesley, 2016), 1.4 Arrays: includes array applications such as shuffling a deck, the coupon collector problem and the sieve of Eratosthenes; the book's website (introcs.cs.princeton.edu) has program code and exercises.
  • A. B. Downey and C. Mayfield, Think Java (2nd ed., O'Reilly, 2019), Chapter 7 “Arrays and References”: explains the concept of a reference, passing arrays to methods and traversal patterns in plain language for beginners; a free online version is available.
  • Oracle, The Java Language Specification, Java SE 21 Edition, Chapter 10 “Arrays”: gives the exact definition of array types, initializers, default values and the behavior of clone.

10.15References

  1. P. Deitel, H. Deitel, Java: How to Program, Early Objects, 11th ed., Pearson, 2018.
  2. Y. D. Liang, Introduction to Java Programming and Data Structures, 13th ed., Pearson, 2024.
  3. Oracle, The Java Tutorials: Arrays.
  4. Oracle, Java SE 21 API: java.util.Arrays; The Java Language Specification, Java SE 21 Edition: Chapter 10. Arrays.
  5. R. Sedgewick, K. Wayne, Computer Science: An Interdisciplinary Approach, Addison-Wesley, 2016: 1.4 Arrays.
  6. T. H. Cormen, C. E. Leiserson, R. L. Rivest, C. Stein, Introduction to Algorithms, 4th ed., MIT Press, 2022.
  7. A. B. Downey, C. Mayfield, Think Java, 2nd ed., O'Reilly, 2019 (free online version).

Related pages: Chapter 10 slides · Study questions · Array Lab simulator · Algorithms lecture notes · Glossary · © Sercan Külcü. All rights reserved.