Object-Oriented Programming with Java · Lecture Notes
Chapter 3.3: Arrays
The exam grades of a class, the readings a sensor delivers every second, or the pixels of a picture all consist of many values of the same kind. Creating a separate variable for each of these values is tiring, and the code breaks when the number of values changes. The array solves this problem: it holds many values of the same type under a single name, in numbered cells. These notes first explain the array concept, the index and the layout of an array in memory. They then cover declaring arrays in Java, initializing them, length, the for-each loop and the java.util.Arrays class. The fact that an array variable is a reference, together with copying and passing arrays to methods, is the most important topic of this part. The following sections deal with the out-of-bounds error, statistical calculations (mean, median, mode), searching and sorting algorithms and their costs, and multidimensional arrays. The notes end with a Tic Tac Toe game built on a two-dimensional character array.
Learning outcomes
- Concept
- Explain that an array holds a fixed number of elements of the same type in consecutive cells, and that elements are accessed by an index that starts at 0.
- Syntax
- Declare one- and multidimensional arrays; create them with
newand with an initializer list; traverse them withlength. - Memory
- Show that an array variable is a reference and that the array lives on the heap; predict the outcome of assignment, copying and passing to a method.
- Errors
- Recognize
ArrayIndexOutOfBoundsExceptionand common compile errors; prevent them with bounds checks. - Algorithms
- Write mean, median, mode, linear and binary search, matching, reversal, selection sort and bubble sort; compare the costs O(1), O(log n), O(n) and O(n²).
- Application
- Fill and print matrices with nested loops, transpose them, and build a Tic Tac Toe game with
char[][].
3.3.1The array concept
In the programs so far, every variable held a single value: a number, a character or a string. In real problems, however, values often come in collections. The grades of fifty students, the temperature measured every minute through a day, or the node voltages in a circuit are such collections. This section defines the array, shows why it is needed, and explains how an array sits in memory.
3.3.1.1What is an array?
An array is a structure that holds a fixed number of values of the same type under a single name, in consecutive cells. Each value in the array is called an element, and the position number of an element in the array is called its index. The index of the first element is 0; the last index of an array with n elements is n − 1.
An array can be thought of as a variable defined with one name that can hold several values. A single variable has one name and one value. An array has a single name but many values. The values are told apart by the index. To reach an element, you write the name of the array followed by the index in square brackets: arr[0], arr[1], arr[2].
Two everyday analogies make the concept concrete. The first is an apartment building. The building has a single address; this corresponds to the name of the array. The flats are numbered, and saying “number 3” is enough to find the right flat. Nobody gives directions like “the second door from the right on the top floor”. The second is an egg carton. The number of cells in the carton is known from the start, and the carton does not grow later. Only things of the same kind are put in each cell. The two basic properties of an array, fixed size and a single type, show up in this analogy.
Indexing from 0 feels odd to beginners. In everyday life counting starts at 1: the first student, the second student. Java, C and the languages derived from them see the index as an offset. The index says how many cells away from the start of the array the element is. The first element is 0 cells away from the start, so its index is 0. This view also makes it easy to compute the address of an element in memory: element number i is i cells away from the starting address.
Let arr = [10, 20, 30, 40, 50]. The array has 5 elements, so the valid indices are 0, 1, 2, 3 and 4.
arr[0] is the first element and its value is 10. arr[4] is the last element and its value is 50. The third element is arr[2]; the index is one less than the ordinal number. There is no element arr[5]. Such an access causes an error at run time in Java.
3.3.1.2Why arrays?
Suppose the average of the grades of fifty students is to be computed. Without an array, a separate variable is needed for each grade:
int grade1 = 70;
int grade2 = 85;
int grade3 = 90;
// ... up to grade50
int sum = grade1 + grade2 + grade3 /* + ... */;This approach has three problems. First, fifty names have to be written one by one in the sum expression. Second, if a student joins the class, the program has to change: a new variable is created and added to the sum. Third, the names of the variables are meaningful only to the programmer. Java does not know the “ordering” relationship between grade1 and grade2. A loop cannot combine grade and i to produce the name grade3.
The array solves these three problems together:
int[] grades = new int[50];
// ... the grades are filled in
int sum = 0;
for (int i = 0; i < grades.length; i++) {
sum += grades[i];
}Here grades is a single name and stands for fifty cells at once. The loop counts i from 0 to 49 and looks at one cell with grades[i] on each pass. The same code works for 5 grades and for 5000 grades; only the size of the array changes. Because grades.length in the loop condition tells how many cells the array has, the condition does not have to be changed by hand either.
grades[i] is written, the current value of i determines which cell is looked at; in the figure, with i = 2, the value 90 is read.The real power of the array can be seen in Figure 3.3.1. The index does not have to be a constant number; it can be a variable or an expression. When grades[i] is written, which cell is looked at is decided not at compile time but at run time, from the value of i. That is why a single line of code can be applied to all the cells in turn inside a loop.
3.3.1.3An array in memory
The elements of an array are not scattered at random places in memory. The cells are laid out side by side, consecutively. Figure 3.3.2 shows an int array with five elements. Above each cell is its index, and inside it is its value.
a with five elements. The cells are next to each other in memory; the indices run from 0 to 4. The variable a holds not the cells themselves but a reference that points to the start of the array.| index | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| element | 13 | −1 | 4 | 2 | 7 |
According to Table 3.3.1, a[1] = −1, a[4] = 7 and a.length = 5. There is no cell a[5]; the valid indices are 0…4. This distinction is the source of most array-related bugs. The length of the array is the number of cells; the last index is one less than the length.
The arrow in the figure matters too. The variable a does not contain five numbers. The variable holds a reference to the region of memory where the five numbers sit. This detail looks unimportant at first sight, but it determines how array assignment, copying and passing to a method work.
3.3.1.4Advantages and disadvantages
The consecutive layout is the source of both the greatest strength and the greatest limitation of the array.
The strengths are the following. The array stores data in an orderly, consecutive way. Access by index is fast: arr[i] is read in the same time for every i. There is no difference between accessing the first element and accessing the millionth. Because the data is grouped, it is easily processed with loops. Memory use is also lean: the array stores only the elements and its length. In structures such as a linked list, the address of the next element is stored next to each element; an array has no such overhead.
The limitations come from the same layout. First, the array has a fixed size: its size cannot be changed after it is created. To add a new element when there is no room left, a new, larger array is created and the old elements are copied into it. Second, inserting in the middle or deleting from the middle requires shifting elements. Third, an array holds elements of only one type.
[10, 15, 20, 30, 40]. (b) The same shifting with arrows: each element is moved to the cell on its right.Figure 3.3.3 shows the cost of insertion. If 15 is to be put at index 1, all elements after index 1 must be moved one cell to the right. The direction of the shifting matters. If shifting goes from left to right, 20 is first written over 30 and 30 is lost. That is why one starts from the last element:
In the array int[] d = {10, 20, 30, 40, 0}; the last cell is empty. Let 15 be inserted at index 1.
The loop for (int i = 3; i >= 1; i--) d[i + 1] = d[i]; first performs d[4] = d[3] (40), then d[3] = d[2] (30), and finally d[2] = d[1] (20). Then d[1] = 15; is written.
The result is [10, 15, 20, 30, 40]. If there are k elements after the insertion position, k shifts are needed. In the worst case, inserting at the front, all the elements move; so insertion needs O(n) work.
For lists whose size changes while the program runs, Java has the ArrayList class. ArrayList still uses an array inside. When the array is full, it creates a larger array and copies the elements into it. The programmer does not see this work, but the cost does not go away; it is only hidden. ArrayList and the other collections are in the java.util package.
3.3.1.5Kinds of arrays and where they are used
Arrays are divided into three groups by the number of dimensions. In a one-dimensional array the elements sit in a single row; int[] grades is of this kind. In a two-dimensional array the elements are arranged in rows and columns; this is a matrix and is written int[][] table. A multidimensional array is written with more square brackets; int[][][] cube is three-dimensional.
The array is the most widespread data structure in programming languages. Three uses often met in electrical and electronic engineering are the following:
- Measurements. Samples taken from a sensor every second are kept in a
double[]array. A digitized audio signal is the same. One second of sound sampled at 44.1 kHz is an array of 44,100 elements. - Matrices. Node equations in circuit analysis, systems of linear equations and transformation matrices are expressed with two-dimensional arrays.
- Images. A grayscale image is a grid of pixels of the form
int[height][width]. A color image needs one more dimension: the red, green and blue channels of each pixel.
A temperature sensor gives 1000 readings, and the readings are kept in the array double[] readings = new double[1000];. How many bytes do the elements take?
In Java every double is 8 bytes. 1000 · 8 = 8000 bytes, that is, about 8 KB is needed. If the same readings were int, each would take 4 bytes and the total would be 4000 bytes. The JVM sets aside a few more bytes for the length and type of the array; this extra is small next to the elements.
This calculation is useful in design. A double array of one million elements takes 8 MB, and a 1000 × 1000 double matrix again takes 8 MB. As the number of dimensions grows, memory grows quickly.
3.3.2Arrays in Java
The array concept is similar in all languages, but the details vary from language to language. How an array is declared in Java, what value the cells start with, where the length is read from, and what an array variable holds are the subjects of this section. The section ends with the java.util.Arrays class, which is often used with arrays.
3.3.2.1Declaring arrays and default values
In Java an array is declared and created with the following general pattern:
Type[] arrayName = new Type[arraySize];The pattern has three parts. Type is the type of the values to be stored in the array: int, double, char, String or any class. arrayName is the name of the array and obeys the rules for naming variables. arraySize says how many elements the array will contain. The size can be a constant, or an int computed at run time.
Two separate things are actually done in the line. The left side, Type[] arrayName, declares an array variable. The right side, new Type[arraySize], sets aside room for the array in the region of memory called the heap. The equals sign writes the reference of this new array into the variable. The variable and the array are different things. This distinction is the basis of all the reference topics ahead.
int[] numbers = new int[5]; // 5 integers
double[] readings = new double[100]; // 100 decimals
String[] names = new String[30];
int n = 12;
char[] letters = new char[n]; // the size comes from a variable
int arr2[] = new int[3]; // C style, valid but not recommendedAll of these lines compile. numbers has five elements, readings a hundred, and names thirty. The size of the array letters comes from a variable: since n is 12, the array has 12 elements. The notation int arr2[] in the last line is a leftover from C. Java accepts it, but it is recommended to write the square brackets next to the type: int[] reads as “int array” and the whole type appears in one place.
The size must be known at the moment of creation. It does not change afterwards. Even if the value of n changes after new int[n] is written, the size of the array stays the same. If the size is negative, the array cannot be created; the program throws NegativeArraySizeException:
Exception in thread "main" java.lang.NegativeArraySizeException: -2
at NegativeSize.main(NegativeSize.java:4)An array of size 0, on the other hand, is valid. new int[0] is an array with no cells and its length is 0. Such an array is useful for expressing “no results at all” without using null.
Default values
The cells of an array created with new do not stay empty. Java writes a default value into each cell according to its type.
| Type | Default value |
|---|---|
int, long, short, byte | 0 |
double, float | 0.0 |
boolean | false |
char | '\u0000' (the character with code 0) |
String and all object types | null |
Default values are interesting when compared with local variables. If a local variable declared as int x; is read without being given a value, the compiler reports the error variable x might not have been initialized. Array cells, on the other hand, are never “valueless”. new int[5] contains five 0s and can be read at once.
The default value of a char array needs separate attention. '\u0000' is not the space character; it is a character with code 0 that is invisible on the screen. The code of the space character is 32. A program that wants to show empty cells as spaces must first fill the char array with ' '. The cells of a String[] array are also not the empty string ("") but null. null is a reference that points to no object, and if a method is called on it, a NullPointerException occurs.
After the line String[] names = new String[30];, names[0].length() is called. Because the cell is null, the program stops with a NullPointerException. new String[30] does not create thirty strings; it creates thirty empty references that can point to thirty strings. A string must be assigned to each cell separately.
3.3.2.2Access and length
The elements of an array are accessed by index, and the index starts at 0. The expression arr[i] is used both to read and to write. On the right of the equals sign it reads, on the left it writes. The size of the array is taken from the length property.
int[] numbers = {10, 20, 30, 40, 50};
int first = numbers[0]; // gets the first element
int second = numbers[1]; // gets the second element
int arraySize = numbers.length; // 5
System.out.println(first + " " + second
+ " " + arraySize);
numbers[1] = 25; // write
int last = numbers[numbers.length - 1]; // 50The program prints the following line:
10 20 5numbers[0] reads the first element (10) and numbers[1] reads the second (20). numbers.length is 5. The " " strings in println separate the numbers from each other; without strings between them, first + second would add and print 30. The line numbers[1] = 25; writes to the second cell. The last line is the general pattern for reading the last element: numbers[numbers.length - 1]. However many elements the array has, this expression gives the last element (an empty array has no last element).
numbers after the write. numbers[1] = 25 has changed the second cell. length = 5 is the number of cells; the last cell is [length − 1], that is, [4].length is not a method but a property (a field) of the array. That is why it is written without parentheses: numbers.length. length() in the String class, on the other hand, is a method and is written with parentheses. The two notations are easily confused:
E_LengthParen.java:4: error: cannot find symbol
System.out.println(a.length());
^
symbol: method length()
location: variable a of type int[]
1 errorThe message says that no method named length() was found in the variable a of type int[]. The reverse is wrong too: if s.length is written for a String variable, the compiler cannot find variable length. A short rule can be kept in mind: no parentheses for arrays, parentheses for strings.
The length field of an array is final, that is, it cannot be changed. The line numbers.length = 10; does not compile. The fixed size of the array is also guaranteed by this rule.
3.3.2.3Initialization
If the elements of the array are known in advance, there is no need to assign each cell one by one. The values are given in braces, separated by commas. This notation is called an array initializer.
int[] numbers = {10, 20, 30, 40, 50}; // with 5 elements
int[] n = {1, 2, 3, 4, 5}; // there are 5 values, so n is an array of 5 elements
int[] m = new int[]{1, 2, 3}; // long form: can be used anywhere
String[] days = {"Mon", "Tue", "Wed"};
char[] vowels = {'a', 'e', 'ı', 'i', 'o', 'ö', 'u', 'ü'};When an initializer list is used, the size is not written. The number of values in the list determines the size: the array n has five values, so n.length is 5. days has three elements and vowels eight. Because Java stores characters as Unicode, Turkish letters such as 'ı', 'ö' and 'ü' are also valid char values.
The initializer list has two forms. The short form, {1, 2, 3}, can be used only on the declaration line. The long form, new int[]{1, 2, 3}, is valid everywhere: in an assignment, in a method call and in return. If you try to declare the array first and fill it later with the short form, the compiler reports an error:
E_ShortAfter.java:4: error: illegal start of expression
a = {1, 2, 3};
^
E_ShortAfter.java:4: error: not a statement
a = {1, 2, 3};
^
E_ShortAfter.java:4: error: ';' expected
a = {1, 2, 3};
^
3 errorsOf the three errors in the message, the real one is the first: illegal start of expression. After the = sign the compiler expects an expression and does not recognize the brace as the start of an expression. The next two messages are confusion caused by this first error. After one error the compiler often produces a series of extra messages; once the first message is fixed, the others disappear too. The correct form is a = new int[]{1, 2, 3};.
Giving both the size and the list is also forbidden. Since the list already determines the size, Java does not allow the possibility that the two pieces of information contradict each other:
E_BothGiven.java:3: error: array creation with both dimension expression and initialization is illegal
int[] a = new int[3]{1, 2, 3};
^
1 errorGiving neither is an error too. If new int[] is written and no list follows, the compiler cannot know how many cells the array will have:
E_NoSize.java:3: error: array dimension missing
int[] a = new int[];
^
1 errorThe values in the list must fit the type of the array. 2.5 cannot be put in an int array, because converting a double to an int discards the fractional part and Java does not do this on its own:
E_Lossy.java:3: error: incompatible types: possible lossy conversion from double to int
int[] a = {1, 2.5, 3};
^
1 errorThe opposite direction causes no problem. double[] d = {1, 2, 3}; is valid; the int values widen to double without loss and the array holds 1.0, 2.0, 3.0. The list double[] c = {-40, 0, 25, 100}; compiles for the same reason.
Out of habit from C, one writes int a[3] = {1, 2, 3};. In Java the size is not part of the type of the variable; javac gives the message ']' expected. In Java the type is only “int array”; how many cells there are is a property of the object, not of the variable. The correct form is int[] a = {1, 2, 3};.
3.3.2.4Code trace: ArrayExample
The following program declares an array, assigns values to its cells one by one, reads two elements, and finally prints all the elements with a loop. Although it is short, it contains all the basic operations on an array.
public class ArrayExample {
public static void main(String[] args) {
// Declaring an array: an integer array with 5 elements
int[] numbers = new int[5];
// Assigning values to the elements of the array
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// Accessing the elements of the array
System.out.println("first element: " + numbers[0]);
System.out.println("third element: " + numbers[2]);
// Printing all the elements of the array in a loop
System.out.print("Elements: ");
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
}
}The output of the program:
first element: 10
third element: 30
Elements: 10 20 30 40 50 new int[5] creates an array of five cells on the heap. Each cell starts with the default value 0. The variable numbers holds the reference to this array. Then five assignment lines fill the cells in turn. The index of the first element is 0, so numbers[0] reads 10. The third element is numbers[2]; the index is one less than the ordinal number.
In the last part print is used. Unlike println, print does not move to the next line; so all the elements are written on the same line with a space between them. A space is also left at the end of the line. The loop starts i at 0 and continues as long as the condition i < numbers.length is true.
i | i < numbers.length | Cell read | Appended to the screen |
|---|---|---|---|
| 0 | 0 < 5 true | numbers[0] = 10 | 10 |
| 1 | 1 < 5 true | numbers[1] = 20 | 20 |
| 2 | 2 < 5 true | numbers[2] = 30 | 30 |
| 3 | 3 < 5 true | numbers[3] = 40 | 40 |
| 4 | 4 < 5 true | numbers[4] = 50 | 50 |
| 5 | 5 < 5 false | — | the loop ends |
new int[5]: all five cells are 0. (b) After three assignments: 10, 20, 30. (c) All five assignments are done. (d) In the printing loop with i = 4: the last valid cell is read. On the next pass i becomes 5 and the condition turns false.Table 3.3.3 shows that the loop checks the condition six times while the body runs five times. At the last check i is 5 and 5 < 5 is false. The last valid index is length − 1 = 4.
The pattern for (int i = 0; i < arr.length; i++) traverses all indices of an array from 0 to length − 1. This pattern is used so often that it is written from memory. Two details of the pattern matter: the start is 0 and the comparison is <. Writing <= is a common mistake and goes beyond the array on the last pass.
The cost of the loop is clear as well. The body runs once per element; in an array with n elements there are n passes. The amount of work grows in proportion to the size of the array. This cost is called O(n).
3.3.2.5The for-each loop
Processing all the elements of an array in order is so common that Java offers a separate loop for it. This loop is called the enhanced for or, in short, the for-each loop.
The for-each loop of the form for (type element : arr) { … } puts a copy of the next element of the array into the variable element on each pass and runs the body. The loop makes as many passes as there are elements in the array. No index is written.
The colon makes it easier to read. The colon is read as “for each … in”: for (int grade : grades) means “for each grade in grades”. The type of the loop variable must be compatible with the element type of the array. A double[] array cannot be traversed with an int variable, because each pass would need a narrowing conversion:
E_ForEachType.java:4: error: incompatible types: possible lossy conversion from double to int
for (int x : d) {
^
1 errorThe following program traverses the same array first with a classic for and then with for-each:
int[] grades = {70, 85, 90};
// Classic for: we have the index
for (int i = 0; i < grades.length; i++) {
System.out.println(i + ". grade: " + grades[i]);
}
// for-each: only the values
int sum = 0;
for (int grade : grades) {
sum += grade;
}
System.out.println("Sum: " + sum);0. grade: 70
1. grade: 85
2. grade: 90
Sum: 245In the classic for loop we have the index; this is how the ordinal information 0., 1., 2. in the output gets written. In the for-each loop there is no index; only the values come. Since the sum needs no index, the second loop is shorter and less prone to errors.
The for-each loop has three properties. First, since no index is written, an out-of-bounds error cannot be made; the loop itself knows where the array ends. Second, the loop is only for reading. Writing grade = 0; does not change the element in the array, it changes only the copy. Third, it is not suitable for jobs that need the index. Writing to the array, reporting the position of an element, or comparing two neighboring elements requires an index. In these cases the classic for is used.
3.3.2.6Code trace: the value comes, not the cell
The following program shows most clearly that the for-each loop is for reading:
int[] scores = {60, 75, 95};
int sum = 0;
for (int p : scores) {
sum += p;
}
System.out.println("Sum: " + sum);
for (int p : scores) {
p = 0;
}
System.out.println(scores[0] + " " + scores[2]);The program prints Sum: 230 and then 60 95. The first loop adds up the three scores. The second loop tries to zero each element, but the array does not change.
| Loop | Pass | p | Body | sum | scores |
|---|---|---|---|---|---|
| — | start | — | — | 0 | [60, 75, 95] |
| 1 | 1 | 60 | sum += p | 60 | [60, 75, 95] |
| 1 | 2 | 75 | sum += p | 135 | [60, 75, 95] |
| 1 | 3 | 95 | sum += p | 230 | [60, 75, 95] |
| 2 | 1 | 60 → 0 | p = 0 | 230 | [60, 75, 95] |
| 2 | 2 | 75 → 0 | p = 0 | 230 | [60, 75, 95] |
| 2 | 3 | 95 → 0 | p = 0 | 230 | [60, 75, 95] |
for-each trace. (a) First pass: the copy of scores[0] goes to p, p = 60. (b) At the end of the last pass sum = 230. (c) In the second loop p = 0 changes only the copy; the 60 in the array stays in place. (d) When the loops are finished the array has not changed at all.Figure 3.3.6 gives the reason visually. p is not a cell of the array but a separate local variable. At the start of each pass the loop copies the value of the next cell into p. p = 0 writes to this local variable; no link remains between the cell and p. To write to the array, a classic for and scores[i] = 0 are needed.
Let every element of the array int[] x = {5, 6, 7}; be multiplied by two.
The wrong way: for (int v : x) v = v * 2;. On the passes v becomes 10, 12 and 14 in turn, but these values are written to copies. Arrays.toString(x) still gives [5, 6, 7].
The right way: for (int i = 0; i < x.length; i++) x[i] = x[i] * 2;. This time the cells themselves are written and the array becomes [10, 12, 14].
3.3.2.7Temperature conversion
Arrays and the for-each loop together give a short way to produce a table. The following program converts four Celsius values to Fahrenheit and Kelvin:
double[] celsiusValues = {-40, 0, 25, 100};
for (double celsius : celsiusValues) {
double fahrenheit = (celsius * 1.8) + 32;
double kelvin = celsius + 273.15;
System.out.println(celsius + " °C = " + fahrenheit
+ " °F = " + kelvin + " K");
}-40.0 °C = -40.0 °F = 233.14999999999998 K
0.0 °C = 32.0 °F = 273.15 K
25.0 °C = 77.0 °F = 298.15 K
100.0 °C = 212.0 °F = 373.15 KcelsiusValues. The values written as int widen to double and are stored as -40.0, 0.0, 25.0, 100.0.double[] celsiusValues = {…}; gathers four values in one array. The list is written with int constants, but because the array is double, the values are stored as -40.0, 0.0, 25.0 and 100.0. The .0s in the output come from this. for (double celsius : celsiusValues) means “for each element in the array”. The body runs four times and the table is produced in one go.
| Pass | celsius | celsius * 1.8 + 32 | celsius + 273.15 |
|---|---|---|---|
| 1 | -40.0 | -72.0 + 32 = -40.0 | 233.14999999999998 |
| 2 | 0.0 | 0.0 + 32 = 32.0 | 273.15 |
| 3 | 25.0 | 45.0 + 32 = 77.0 | 298.15 |
| 4 | 100.0 | 180.0 + 32 = 212.0 | 373.15 |
The 233.14999999999998 in the first row looks like a bug, but Java works correctly. Floating-point numbers are stored in binary. Many decimal numbers such as 273.15 have no finite representation in binary. The number is stored as the nearest representable value, and a small rounding difference shows up in the result of the operation. For the same reason 0.1 + 0.2 gives 0.30000000000000004.
This difference can be hidden by limiting the number of digits when printing: System.out.printf("%.2f K%n", kelvin). Here there is a detail specific to Turkey. printf formats the number according to the language setting of the computer. On a computer set to Turkish the output is 233,15 K; the decimal separator is a comma. println, on the other hand, always uses a point, independent of the setting.
Comparing floating-point numbers with ==. The expression -40 + 273.15 == 233.15 gives false. The equality of two floating-point numbers is checked by testing whether the difference between them is less than a small threshold: Math.abs(a - b) < 1e-9.
3.3.2.8An array variable is a reference
This is the most important and most misunderstood property of arrays. When int x = 5; is written, the number 5 sits inside the variable x. When int[] a = {1, 2, 3}; is written, however, the three numbers do not sit inside a. The three numbers are in an array on the heap; a holds the address of that array, that is, its reference.
A reference is a value that points to the location of an object in memory. Arrays, strings and all class objects are reference types: variables of these types hold not the object itself but a reference to the object. If two variables point to the same object, one is an alias of the other.
int[] a = {1, 2, 3};
int[] b = a; // not a copy!
b[0] = 99;
System.out.println(a[0]);
int[] c = a.clone(); // a real copy
c[1] = 77;
System.out.println(a[1] + " " + c[1]);
System.out.println(a == b);
System.out.println(a == c);The program prints four lines: 99, 2 77, true and false. The reason for each line can be seen in Figure 3.3.8.
a holds its reference. (b) b = a copies only the reference; both variables point to the same array. (c) Because b[0] = 99 changes the shared array, a[0] also becomes 99. (d) clone() creates a new array on the heap; c[1] = 77 changes only this copy.Let us follow the lines in order. int[] b = a; does not create a new array. The value of a on the right-hand side is a reference, and this reference is copied into b. Now both variables point to the same array. b[0] = 99 writes to the first cell of the shared array. When a[0] is read, the same cell is looked at, so 99 comes out.
a.clone(), on the other hand, produces a real copy. A new array is created on the heap and the elements are copied into it. Because a[0] is 99 at the moment of copying, the copy is [99, 2, 3]. c[1] = 77 changes only the copy; in the original array a[1] is still 2.
The last two lines show the meaning of the == operator on arrays. == compares references, that is, addresses. a == b is true because both point to the same array. a == c is false. Even if the array in c holds the same contents as that of a at that moment, it is a different object. To compare contents, Arrays.equals is used.
Passing an array to a method
In Java all arguments are passed by value: a copy of the argument goes to the method. When an int is passed, a copy of the number goes. When an array is passed, a copy of the reference goes. The copied reference also points to the same array. So if the method changes the cells of the array, the change is visible in the caller's array.
Let the following method and call be given:
static void modify(int[] d, int x) { d[0] = 100; x = 100; }int[] a = {1, 2, 3}; int x = 1; modify(a, x);
After the call a[0] is 100 and x is 1. d is a copy of the reference in a and points to the same array; d[0] = 100 writes to a cell of that array. The x in the method is a copy of the x in main. Writing 100 to the copy does not affect the original variable.
This rule has one more consequence. If a new array is assigned to the parameter inside the method, for example d = new int[]{0, 0};, only the local copy is bound to the new array. The caller's variable keeps pointing to the old array. Whatever the method writes to d from then on goes to the new array, and the caller does not see it.
Mistaking assignment for copying. If int[] backup = grades; is written and grades is sorted afterwards, backup is sorted too, because there is only a single array. For a real copy, grades.clone() or Arrays.copyOf(grades, grades.length) is used.
3.3.2.9The java.util.Arrays class
Java offers ready-made methods for common jobs with arrays. These methods are in the java.util.Arrays class, and to use them import java.util.Arrays; is written at the top of the file. All the methods are static; they are called with the class name, as in Arrays.sort(d).
int[] arr = {5, 3, 8, 1};
System.out.println(Arrays.toString(arr));
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
int[] copy = Arrays.copyOf(arr, 6);
System.out.println(Arrays.toString(copy));
int[] filled = new int[4];
Arrays.fill(filled, 7);
System.out.println(Arrays.toString(filled));
int[] x = {1, 2};
int[] y = {1, 2};
System.out.println((x == y) + " " + Arrays.equals(x, y));
System.out.println(Arrays.binarySearch(arr, 5));[5, 3, 8, 1]
[1, 3, 5, 8]
[1, 3, 5, 8, 0, 0]
[7, 7, 7, 7]
false true
2Line by line: Arrays.toString turns the array into readable text. Arrays.sort sorts the array from smallest to largest. The sorting is done in place; no new array is returned, the given array changes. Arrays.copyOf(arr, 6) creates a new array with 6 cells and copies the old elements into the first four cells; the extra cells get the default value 0. If a new length smaller than the old one is given, the array is cut: copyOf(arr, 2) gives [1, 3].
Arrays.fill(filled, 7) writes the same value to all the cells. x and y are two separate arrays holding the same elements: x == y is false and Arrays.equals(x, y) is true. Arrays.binarySearch(arr, 5) on the last line searches for 5 in the sorted array and returns its index: 2.
| Method | Purpose |
|---|---|
Arrays.toString(d) | Turns the array into text in the form [5, 3, 8, 1]. |
Arrays.deepToString(m) | Turns nested arrays (matrices) into text. |
Arrays.sort(d) | Sorts the array in place, from smallest to largest. |
Arrays.binarySearch(d, x) | Returns the index of x in a sorted array; if it is absent, a negative number is returned. |
Arrays.copyOf(d, n) | Creates a new array with n cells and copies into it; extra cells get the default value. |
Arrays.fill(d, v) | Writes v to all the cells. |
Arrays.equals(a, b) | Compares the lengths and the elements of two arrays. |
Printing an array directly with println does not give the expected result. System.out.println(arr) prints not the elements but an identifier such as [I@1c20c684. The leading [I means “int array”; the hexadecimal number after @ is the identity code of the object and may change on every run. To see the elements, Arrays.toString(arr) is used.
Two more details should be known. First, arrays have no search method such as indexOf. To search an unsorted array a loop is written; this method is called linear search. Second, binarySearch works correctly only on a sorted array. If the sought value is absent, the result is a negative number that also encodes the position where the value would be inserted. If 4 is searched for in the sorted array [1, 3, 5, 8], the result is −3. On an unsorted array the result is meaningless, and no warning is given either.
The costs of the methods differ. toString, fill, copyOf and equals touch each element once, so they are O(n). binarySearch is O(log n), and sort is O(n log n) on average. The one-line form of sort does not mean that the work behind it is small.
3.3.3Memory and errors
The most frequent run-time error in programs that use arrays is going outside the bounds of the array. To understand this error you first need to know where an array lives in memory. This section explains how Java divides memory, how unused arrays are cleaned up, and how bounds errors are caught.
3.3.3.1Where are arrays in memory?
The memory of a running Java program is divided into two main regions. The stack holds the local variables of method calls. Every method call opens a frame on the stack; when the method ends, the frame is removed and the variables in it disappear. The heap is the region where objects created with new live. An object on the heap can live on after the method that created it has ended.
In Java all arrays are on the heap. Only the reference variables that point to the arrays sit on the stack. In C and C++ the situation is different. An array declared as int a[10]; sits on the stack. A raw array allocated with malloc or new[] is on the heap, and when the programmer is done with it, it must be released by hand with free or delete[] (in C++, std::vector does this by itself). In Java there is no such distinction; releasing is automatic too.
String[] plates = {"", "Adana", "Adıyaman", "Afyon"};
System.out.println(plates[1]);
int[] dynamicArr = new int[10]; // space is allocated on the heap
System.out.println(dynamicArr.length);
dynamicArr = null; // reference cut
System.out.println(dynamicArr == null);The program prints Adana, 10 and true in turn. The first cell of the plates array is the empty string; so the province with plate code 1 sits at plates[1], and the index and the plate code coincide. This is a practical compromise with indexing from 0. The size of dynamicArr could also have been given at run time; but once the array is created, its size is fixed.
String[] are in fact references to separate String objects. (b) dynamicArr = null cuts the link; the int array becomes unreachable. (c) When the method ends the stack frame is removed; arrays with no other reference are collected in time.The line dynamicArr = null; does not delete the array. It only cuts the link between the variable and the array. As seen in Figure 3.3.9, the array stays on the heap, but there is no longer any reference that reaches it. The JVM's garbage collector finds such unreachable objects and reclaims their memory.
The garbage collector is the JVM component that finds objects that no reference points to and gives back the memory they occupy. Java has no release command such as free or delete; memory management is automatic.
It is not defined when the garbage collector will run. An array becoming unreachable does not mean that the memory will be freed at once. The JVM does the collecting at a suitable moment. What matters for the programmer is not to hold on to unneeded references. If a variable that points to a large array lives until the end of the program, the array lives too.
What happens to the first array after the lines int[] p = new int[1000]; int[] q = p; p = new int[5]; q = null;?
In the first line an array of 1000 cells is created and p points to it. In the second line q points to the same array too. The third line binds p to a new array of 5 cells; the first array is still pointed to by q. The fourth line cuts this last link as well.
Now no reference reaches the array of 1000 cells, and the garbage collector can collect it. The array has not shrunk: p = new int[5] creates a new array and does not change the old one.
3.3.3.2The index-out-of-bounds error
The valid indices of an array lie between 0 and length − 1. If an array is accessed with an index outside this range, Java throws an ArrayIndexOutOfBoundsException at run time. This exception is a subclass of IndexOutOfBoundsException. If the exception is not caught, the program stops at that line.
ArrayIndexOutOfBoundsException is the exception the JVM throws when an array is accessed with a negative index or with an index equal to or greater than length. The compiler does not check index values; the check is made at run time on every access.
This behavior sets Java apart from C. In C an access such as a[10] is not checked. The program reads or writes the memory right behind the array. The result is a random value, the corruption of another variable, or an obscure bug that shows up much later. Java, on the other hand, catches the error on the very line where it occurs and stops the program. The program crashes, but it does not silently produce a wrong result.
int[] arr = {10, 20, 30, 40, 50};
int index = 5;
// Checking the array length
if (index >= 0 && index < arr.length) {
int value = arr[index];
System.out.println("Value: " + value);
} else {
System.out.println("Invalid index: " + index);
}
// Unchecked access:
System.out.println(arr[index]);Invalid index: 5
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at OutOfBounds.main(OutOfBounds.java:13)The first part of the program shows the pattern for safe access: before the index is used, it is checked with the condition index >= 0 && index < arr.length. Because 5 is not a valid index, the else branch runs and Invalid index: 5 is printed. The last line uses the same index without a check, and the exception occurs.
The exception message says everything needed to find the error. Index 5 is the faulty index. out of bounds for length 5 is the length of the array. The line at OutOfBounds.main(OutOfBounds.java:13) gives the class, the method and the line number of the file where the error occurred. When you meet a bounds error, this line is the first place to look.
A negative index causes the same exception. In some languages d[-1] means the last element; in Java it does not:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3
at Negative.main(Negative.java:4)Thinking the last index is length. a[a.length] is always out of bounds; the last element is a[a.length - 1]. The same error appears in a loop condition as i <= a.length. For an array with three elements the message is Index 3 out of bounds for length 3: the faulty index and the length are equal.
3.3.3.3The classic bug: a loop with <=
The most common source of the out-of-bounds error is the loop condition:
int[] arr = new int[3];
for (int i = 0; i <= arr.length; i++) {
arr[i] = i * 10;
}Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at BoundsLoop.main(BoundsLoop.java:5)i = 3, the condition 3 <= 3 stays true and an attempt is made to write to the fourth cell that does not exist, arr[3].The loop writes 0, 10 and 20 to the cells for i = 0, 1, 2. When i becomes 3, 3 <= 3 is true and the body runs once more. arr[3] does not exist and the exception is thrown. The correct condition is i < arr.length. Writing a constant, for example i < 3, gives the right result for this array; but if the size of the array changes, the code breaks. Using length ties the condition to the array.
To see in which pass the error occurs, let us trace a similar program step by step:
int[] square = new int[4];
for (int i = 0; i <= square.length; i++) {
square[i] = i * i;
}
System.out.println("done");i | i <= square.length | Body | square |
|---|---|---|---|
| — | — | start | [0, 0, 0, 0] |
| 0 | 0 <= 4 true | square[0] = 0 | [0, 0, 0, 0] |
| 1 | 1 <= 4 true | square[1] = 1 | [0, 1, 0, 0] |
| 2 | 2 <= 4 true | square[2] = 4 | [0, 1, 4, 0] |
| 3 | 3 <= 4 true | square[3] = 9 | [0, 1, 4, 9] |
| 4 | 4 <= 4 true | square[4] does not exist: exception | the program stops |
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
at Square.main(Square.java:5)Table 3.3.7 shows the exact place of the error. The last valid cell is filled on the fourth pass. On the fifth pass 4 <= 4 is also true; had < been written, the loop would end here. The JVM throws the exception at the access square[4] and the program stops on this line. "done" is never printed, because the exception is not caught and so the following lines are not reached.
i = 3: the last valid cell is filled with square[3] = 9. (b) i = 4: square[4] does not exist; the JVM throws ArrayIndexOutOfBoundsException.The root of the error is the habit of counting. Someone who counts from 1 to 4 writes <=; someone who starts at 0 and counts four elements must write < 4. When the two patterns are mixed up, either the first element is skipped or the last pass goes beyond the array. for (int i = 1; i <= d.length; i++) does both: d[0] is never written, and the last pass throws the exception.
3.3.3.4An array that was never created: null
If an array variable is declared and no array is bound to it, or if null is assigned to it explicitly, the variable points to no array. Accessing a cell through such a variable causes a NullPointerException:
Exception in thread "main" java.lang.NullPointerException: Cannot load from int array because "<local1>" is null
at Npe.main(Npe.java:4)Since Java 15 these messages are “helpful” by default: they also say what is null. The "<local1>" in the message is local variable number 1 of the method, that is, a. By default the compiler does not write local variable names into the .class file. If the code is compiled with javac -g, or if debugging information is added as in most IDEs, the message becomes because "a" is null directly.
The difference between an array and null is the difference between an empty array and absence. int[] a = new int[0]; is an array and a.length gives 0. int[] a = null; is not an array; even a.length throws a NullPointerException.
3.3.4Statistics examples
The three best-known measures for summarizing a data set are the mean, the median and the mode. All three are computed naturally with arrays, and each shows a different technique. The mean adds up in a single pass, the median relies on sorting, and the mode compares neighbors in a sorted array. All three programs start with the same section that reads the data from the user.
3.3.4.1Reading an array from the user
import java.util.Scanner;
public class AverageCalculation {
public static void main(String[] args) {
// Get the size of the array from the user
Scanner scanner = new Scanner(System.in);
System.out.print("enter size: ");
int size = scanner.nextInt();
// Get the elements from the user and build the array
double[] arr = new double[size];
for (int i = 0; i < size; i++) {
System.out.print((i + 1) + ". element: ");
arr[i] = scanner.nextDouble();
}
// ... calculations with the array
}
}In a sample run the user first enters the size and then four values:
enter size: 4
1. element: 7
2. element: 3
3. element: 9
4. element: 5In this program the size of the array is not known at compile time. scanner.nextInt() reads the number the user typed, and new double[size] creates the array with that size. The size is decided at run time, but it does not change once the array has been created. If the user wants to enter more values, a new array is needed.
The (i + 1) in the prompt line is a small but important detail. The user counts from 1 and expects to see “1. element”. The code counts from 0 and writes the value to arr[i]. i + 1 is used on the screen and i in the code. The parentheses are also needed: (i + 1) + ". element: " does the addition first. Without parentheses, i + 1 + "." would be evaluated from left to right and still give the right result; but a form such as "" + i + 1 would produce "01". The parentheses show the intention clearly.
The nextDouble() method of Scanner reads the decimal separator according to the language setting of the computer. On a computer set to Turkish, 7,5 is accepted and 7.5 causes an InputMismatchException. With integer input this problem does not arise.
3.3.4.2Mean
The mean (arithmetic mean) is the sum of the values divided by the number of values. After the reading section, the program runs two more loops: one adds up, the other prints.
Scanner scanner = new Scanner(System.in);
System.out.print("enter size: ");
int size = scanner.nextInt();
double[] arr = new double[size];
for (int i = 0; i < size; i++) {
System.out.print((i + 1) + ". element: ");
arr[i] = scanner.nextDouble();
}
double sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
double mean = sum / size;
System.out.print("Elements: ");
for (int i = 0; i < size; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("Mean: " + mean);enter size: 4
1. element: 7
2. element: 3
3. element: 9
4. element: 5
Elements: 7.0 3.0 9.0 5.0
Mean: 6.0| Step | i | Operation | arr | sum |
|---|---|---|---|---|
| reading | — | size = 4, new double[4] | [0.0, 0.0, 0.0, 0.0] | — |
| reading | 0 | arr[0] = 7.0 | [7.0, 0.0, 0.0, 0.0] | — |
| reading | 1 | arr[1] = 3.0 | [7.0, 3.0, 0.0, 0.0] | — |
| reading | 2 | arr[2] = 9.0 | [7.0, 3.0, 9.0, 0.0] | — |
| reading | 3 | arr[3] = 5.0 | [7.0, 3.0, 9.0, 5.0] | — |
| summing | — | sum = 0 | same | 0.0 |
| summing | 0 | sum += arr[0] | same | 7.0 |
| summing | 1 | sum += arr[1] | same | 10.0 |
| summing | 2 | sum += arr[2] | same | 19.0 |
| summing | 3 | sum += arr[3] | same | 24.0 |
| division | — | mean = 24.0 / 4 | same | 6.0 |
new double[size]: all four cells are 0.0. (b) Two values have been read. (c) Four values have been read: 7.0, 3.0, 9.0, 5.0. (d) The last pass of the summing loop: sum = 24.0.The floating-point division is the result of a design decision. Because sum is declared double, sum / size is the quotient of a double and an int. The int is first widened to double and real division is performed: 24.0 / 4 = 6.0. If the sum were int, the difference would show. For the set 7, 3, 9, 5, 1, 4, 29 / 6 gives 4 with integer division; the correct value is 4.833….
Computing the mean with two ints and assigning the result to a double: double mean = sum / arr.length;. The division is performed before the assignment, between two ints, and the fraction has already been discarded; 29 / 6 first becomes 4 and then becomes 4.0. The right way is to convert before dividing: sum / (double) arr.length.
The cost of the program is clear. The reading, summing and printing loops each make n passes; the total work is of the order 3n, which is O(n). The sum could also have been accumulated in the reading loop; merging the two loops reduces the number of passes but does not change how the cost grows.
3.3.4.3Median
The median is the value in the middle of a sorted data set. If the number of elements is odd, it is the element exactly in the middle; if even, it is the mean of the two middle elements.
The median is not affected by extreme values as much as the mean is. The mean of the values 3, 4, 5, 6 and 100 is 23.6 and is close to none of the data. Its median is 5. That is why the median is preferred for measurements that contain a few extreme values, such as income, house prices or network latency.
// size and array are read as in AverageCalculation
Arrays.sort(arr); // Sort the array
double median;
if (size % 2 == 0) { // Even number of elements
int mid1 = size / 2 - 1;
int mid2 = size / 2;
median = (arr[mid1] + arr[mid2]) / 2;
} else { // Odd number of elements
median = arr[size / 2];
}
System.out.println("Median: " + median);entered: 7 3 9 5 1
Sorted elements: 1.0 3.0 5.0 7.0 9.0
Median: 5.0The first step of the calculation is sorting. The median is defined on the sorted order; the element in the middle of an unsorted array is a random value. Figure 3.3.13 shows this: the cell in the middle in the order entered is 9.0, but the median is 5.0.
Arrays.sort, size 5 (odd): arr[5 / 2] = arr[2] = 5.0. (c) Size 4 (even; inputs 7 3 9 5): mid1 = 1, mid2 = 2 and the median is (5.0 + 7.0) / 2 = 6.0.If the size is odd, the middle index is size / 2. For size 5, 5 / 2 gives 2 with integer division, not 2.5. Here the fact that integer division discards the fraction is useful. With indices starting at 0, the middle of 5 elements really is at index 2: there are two elements on its left and two on its right.
If the size is even, there is no single middle element. For size 4 the two middle indices are 4 / 2 − 1 = 1 and 4 / 2 = 2. If the inputs are 7, 3, 9, 5, the sorted array is [3.0, 5.0, 7.0, 9.0] and the median is (5.0 + 7.0) / 2 = 6.0. Because the array is double, the division is floating-point. If the same code were written with an int array, an expression such as (4 + 5) / 2 would give 4; the right value is 4.5, and / 2.0 must be written.
The line double median; in the code is outside the branches. This placement is necessary. If the variable were declared inside the if and else branches, each would live only in its own block. The println outside the branches could not see it:
E_Median.java:10: error: cannot find symbol
System.out.println("Median: " + median);
^
symbol: variable median
location: class E_Median
1 errorDeclaring the variable outside and giving it a value in only one branch is not enough either. Without the else branch the compiler would see that the variable stays without a value when the if condition is false and would report variable median might not have been initialized. In the form used in the code, both branches assign a value, so there is no problem.
Arrays.sort has a side effect: it changes the array in place. After the median is computed, the order entered by the user is lost. If the order is needed later, the sorting is done on a copy: double[] sorted = arr.clone(); Arrays.sort(sorted);.
The cost is determined by the sorting. Reading the middle element is O(1), but Arrays.sort does O(n log n) work. The median is a more expensive measure than the mean.
3.3.4.4Mode
The mode is the value that occurs most often in a data set. The mode of the set 4 2 7 2 4 2 9 is 2; 2 occurs three times.
A plain way to find the mode is to count, for each value, how many times it occurs by scanning the whole array. This way makes n comparisons for each of the n values and costs O(n²). The program in the slides takes a smarter way. It first sorts the array, so that equal values come next to each other. Then in a single pass it finds the longest “run”.
int modeValue = arr[0];
int modeCount = 1;
int currentValue = arr[0];
int currentCount = 1;
for (int i = 1; i < size; i++) {
if (arr[i] == arr[i - 1]) {
currentCount++;
} else {
currentCount = 1;
currentValue = arr[i];
}
if (currentCount > modeCount) {
modeCount = currentCount;
modeValue = currentValue;
}
}Four variables keep track of two runs. currentValue and currentCount are the value and the length of the run being counted at the moment. modeValue and modeCount are the value and the length of the longest run seen so far. The loop starts from i = 1, because each element is compared with the one before it, and the first element has no predecessor. The first element is initially counted as both the current run and the longest run.
Two decisions are made on every pass. First: if the element equals the previous one, the run grows; if not, a new run starts and the length becomes 1. Second: if the current run is longer than the longest run, the longest run is updated. The result is printed like this:
// Print the result
System.out.println("Sorted elements: " + Arrays.toString(arr));
System.out.print("Mode: " + modeValue);
System.out.println(" (count: " + modeCount + ")");Sorted elements: [2, 2, 2, 4, 4, 7, 9]
Mode: 2 (count: 3)i = 3: arr[3] = 4 differs from the previous one (2) and a new run starts.i | Comparison | Current run | Longest run |
|---|---|---|---|
| — | start | 2 × 1 | 2 × 1 |
| 1 | 2 == 2 | 2 × 2 | 2 × 2 (updated) |
| 2 | 2 == 2 | 2 × 3 | 2 × 3 (updated) |
| 3 | 4 ≠ 2 | 4 × 1 | 2 × 3 |
| 4 | 4 == 4 | 4 × 2 | 2 × 3 |
| 5 | 7 ≠ 4 | 7 × 1 | 2 × 3 |
| 6 | 9 ≠ 7 | 9 × 1 | 2 × 3 |
| 7 | 7 < 7 false: the loop ends. Mode 2, count 3. | ||
The > sign in the update condition decides the case of a tie. If two runs have the same length, the run that comes later cannot overtake the earlier one; the first one found is kept. Because the array is sorted, this means that the smallest of the equally frequent values is chosen. Had >= been written, the last one found, that is, the largest, would have been chosen. If it is necessary to report that there may be several modes, additional counting is needed.
What is the mode of the sorted array {2, 2, 6, 6, 6, 9}?
The first run is 2 × 2; the longest run is 2 × 2. At i = 2, 6 starts (6 × 1). At i = 3 the run becomes 6 × 2, but 2 > 2 is false and the longest run stays 2. At i = 4 the run becomes 6 × 3. 3 > 2 is true and the longest run is updated. 9 starts a new run.
The program prints Mode: 6 (count: 3).
The cost of this method has two parts: O(n log n) sorting and O(n) scanning. The total is O(n log n), which is much better than the O(n²) cost of the plain counting method. Sorting here is a preparation step; the calculation that follows relies on equal values standing next to each other.
3.3.5Array algorithms
The most frequent jobs on an array are searching, comparing, sorting and reordering. This section gives the basic algorithms for these jobs and counts how much work each of them does. The counting leads to the O notation, the common language for comparing algorithms.
3.3.5.1Linear search
Linear search is a search method that compares the sought value with every element of the array in turn, from the start to the end. When the value is found the search ends; if the end of the array is reached, the value is not there.
static boolean linearSearch(int[] arr, int target) {
for (int element : arr) {
if (element == target) {
return true;
}
}
return false;
}
// inside main:
int[] arr = {10, 20, 30, 40, 50};
boolean result = linearSearch(arr, 30);The linearSearch method takes two parameters: the array to search and the target value. The for-each loop puts the elements into element in turn. If an element equals the target, return true ends both the loop and the method at once. If the loop ends without finding any equality, the last line is reached and false is returned. Because the search needs no index, for-each is suitable here.
| Pass | element | element == target | Result |
|---|---|---|---|
| 1 | 10 | 10 == 30 false | next element |
| 2 | 20 | 20 == 30 false | next element |
| 3 | 30 | 30 == 30 true | return true |
element = 10, not the target. (b) Third pass: 30 is found and the method returns true. 40 and 50 are never looked at.When main calls linearSearch(arr, 30), the reference to the array and the value 30 go to the method. The array is not copied. Three comparisons are enough to find the result; the method frame is removed from the stack and result becomes true. If the target were 35, all five comparisons would turn out false and the method would return false.
The same search can be done without writing a method. This time break is used to leave the loop:
int[] arr = {10, 20, 30, 40, 50};
// Searching for a particular element in an array
int key = 30;
boolean found = false;
for (int element : arr) {
if (element == key) {
found = true;
break;
}
} // This operation has O(n) complexity.break leaves the loop the moment the target is found. In this example only three elements are looked at and found becomes true. Without break the result would still be correct, but the loop would needlessly look at 40 and 50 as well. It is important that found starts as false: if no equality is found, the right answer is “absent”.
The answer to “is it there?” alone may not be enough as a search result. If you need to know where the element is, the index is returned and this time a classic for is used: for (int i = 0; i < d.length; i++) if (d[i] == target) return i; return -1;. Since −1 cannot be a valid index, it is used to mean “absent”. If 5 is searched for in the array {12, 7, 30, 5, 18} the result is 3, and if 99 is searched for it is −1.
3.3.5.2The cost of linear search
Measuring the speed of an algorithm in seconds is misleading; the same code takes less time on a fast computer. Instead, the basic operations that the algorithm performs are counted. In linear search the basic operation is a comparison.
The number of comparisons depends on where the target is. In the best case the target is the first element and one comparison is enough. In the worst case the target is at the end of the array or absent; in an array with n elements, n comparisons are made. If the target is at a random place in the array, the average number of comparisons is about n/2.
Time complexity describes how the amount of work an algorithm does grows with the input size n. Big-O notation gives the shape of this growth; it drops constant factors and smaller terms. If the amount of work grows in proportion to n, the algorithm is O(n).
The time complexity of linear search is O(n). The difference between n/2 and n is unimportant in big-O notation: both double when the array doubles. On an unsorted array nothing better can be done. “Absent” cannot be answered without looking at every element, because an element that was not looked at might be the target.
3.3.5.3Binary search
If the array is sorted, the situation changes. When looking up a name in a phone book, nobody starts from the first page. The book is opened in the middle; if the name sought comes before the one on that page, one moves to the left half, and if it comes after, to the right half. At each look the search space is cut in half.
Binary search is a method that looks at the middle element of a sorted array and continues the search in the left half if the target is smaller and in the right half if it is larger. The search space halves at every step. It works only on a sorted array.
static int binarySearch(int[] arr, int target) {
int lo = 0, hi = arr.length - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] == target) {
return mid; // found
} else if (target < arr[mid]) {
hi = mid - 1; // left half
} else {
lo = mid + 1; // right half
}
}
return -1; // search space exhausted
}
// inside main:
int[] arr = {3, 9, 14, 27, 42, 48, 55, 61, 70};
System.out.println(binarySearch(arr, 48));
System.out.println(binarySearch(arr, 50));5
-1The method keeps the search space in two variables: lo is the first and hi the last index of the space. At the start the space is the whole array. On each pass the middle index is found with (lo + hi) / 2; integer division discards the fraction. If the middle element is the target, its index is returned. If the target is smaller, the right half is eliminated and hi = mid - 1. If the target is larger, the left half is eliminated and lo = mid + 1. When lo passes hi, the space is empty and −1 is returned.
| Target | Pass | lo | hi | mid | arr[mid] | Decision |
|---|---|---|---|---|---|---|
| 48 | 1 | 0 | 8 | 4 | 42 | 48 > 42: lo = 5 |
| 48 | 2 | 5 | 8 | 6 | 55 | 48 < 55: hi = 5 |
| 48 | 3 | 5 | 5 | 5 | 48 | found: returns 5 |
| 50 | 1 | 0 | 8 | 4 | 42 | 50 > 42: lo = 5 |
| 50 | 2 | 5 | 8 | 6 | 55 | 50 < 55: hi = 5 |
| 50 | 3 | 5 | 5 | 5 | 48 | 50 > 48: lo = 6 |
| 50 | — | 6 | 5 | — | — | 6 <= 5 false: returns −1 |
Table 3.3.11 gives the two searches side by side. For 48 the middle indices are 4 (42), 6 (55) and 5 (48). Three comparisons are enough. For 50 the same three steps are taken, then lo becomes 6 and hi becomes 5. The space is empty, and it is settled that 50 is not in the array. Linear search would have reached the same result only with nine comparisons.
The size of the gain shows as the array grows. Because the space of n elements halves at every step, it shrinks to a single element in at most about log₂ n steps. The time complexity of binary search is therefore O(log n). For n = 1000 at most 10 comparisons are needed. For n = 1,000,000 this number is at most 20. Linear search could make 1000 and 1,000,000 comparisons for the same arrays.
This has a price: the array must be sorted. Sorting takes O(n log n) work and is not worth doing for a single search. If many searches will be made on the same array, it pays to sort once and then do each search in O(log n). Arrays.binarySearch uses the same method; on an unsorted array its result is meaningless.
Writing the loop condition as lo < hi. In that case, when a single element is left in the space (lo == hi), the loop ends without looking at that element. Exactly this happens in the third pass of the search for 48. The method returns −1 although 48 is in the array. The correct condition is lo <= hi. In the same way, writing hi = mid is also wrong: the space might not shrink and the loop would run forever.
3.3.5.4Matching
To find the common elements of two arrays, each element is compared with every element of the other array. This job is done with two nested loops:
static void match(int[] arr1, int[] arr2) {
for (int element1 : arr1) {
for (int element2 : arr2) {
if (element1 == element2) {
System.out.println("Match: " + element1);
}
}
}
}The call match(new int[]{3, 7, 1}, new int[]{5, 1, 3, 8}) prints Match: 3 and Match: 1. In the call the arrays are created directly with the long form new int[]{…}, without being assigned to variables. The short form {3, 7, 1} cannot be used here.
While the outer loop has element1 = 3, the inner loop compares it with all four elements of arr2. When a match is found it is printed, but the inner loop does not stop; it looks at the remaining elements too. The same work is repeated for element1 = 7 and 1. Figure 3.3.17 shows all the comparisons as a table. A total of 3 × 4 = 12 comparisons are made.
If the arrays have n and m elements, n · m comparisons are needed. If both arrays have n elements, this is n², and matching costs O(n²). Nested loops are usually the sign of this quadratic growth. There is a faster way too: the second array is sorted first and each element of the first array is searched for with binary search. The cost of this way is O(n log n).
3.3.5.5Complexity: O(1), O(n), O(n²)
Before comparing the costs of algorithms, the cost of the most basic operation, access by index, must be understood. arr[2] and arr[1000000] are read in the same time. The reason for this is the layout of the array in memory.
int takes 4 bytes. The address of arr[2] is found with a single calculation: 1000 + 2 × 4 = 1008.Because the cells are consecutive and of equal size, the address of element number i is computed with one multiplication and one addition:
address(arr[i]) = start + i × element size
For int the element size is 4 bytes. If the start address is 1000, arr[2] sits at 1008 and arr[1000000] at 4,001,000. Both calculations take the same time; the processor does not need to look at the earlier elements. The cost of access is independent of the size of the array, and this is written O(1), that is, constant time. One reason why the index starts at 0 is this formula: if the index started at 1, one more subtraction would be needed on every access.
| Operation | Complexity | for n = 1000 |
|---|---|---|
Access arr[i] | O(1), constant | 1 |
| Binary search (sorted array) | O(log n), logarithmic | ≤ 10 |
| Linear search | O(n), linear | ≤ 1000 |
| Reversal | O(n), linear | 500 swaps |
| Matching (nested) | O(n²), quadratic | 1.000.000 |
| Selection sort | O(n²), quadratic | ≈ 500,000 (exactly 499,500) |
Table 3.3.12 shows the size of the differences. O(n²) algorithms are inefficient on large data sets. If n grows tenfold, the running time of an O(n) algorithm grows tenfold and that of an O(n²) algorithm grows a hundredfold. A quadratic algorithm that sorts 1000 elements in one second takes about three hours for 100,000 elements. O(1) access, on the other hand, is not affected by the input size at all.
3.3.5.6Selection sort
Selection sort is a sorting method that, on each pass, finds the smallest element in the unsorted part of the array and moves it to the start of this part. After each pass the sorted part grows by one element.
static void selectionSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int minIdx = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
}
int tmp = arr[minIdx];
arr[minIdx] = arr[i];
arr[i] = tmp;
}
}i = 2 the smallest element of the unsorted part, 22, is found and exchanged with the 64 at the start of that part.The outer loop counts i from 0 to length − 2. i is the start of the unsorted part. On each pass minIdx first becomes i; that is, the first element of the part is taken to be the smallest. The inner loop j scans the rest of the part and updates minIdx whenever it sees a smaller element. When the inner loop ends, the smallest element is at arr[minIdx] and is exchanged with arr[i].
The swap is done with three assignments, with the help of a temporary variable. If arr[i] = arr[minIdx]; arr[minIdx] = arr[i]; were written, the first assignment would erase the old value of arr[i] and both cells would hold the same value. tmp keeps the old value. It is enough for the outer loop to make length − 1 passes: once n − 1 elements are in place, the last element is automatically in the right place.
The sorting is done on the array itself and the method is void. Because the reference to the array comes into the method, the swaps change the caller's array. This point sets a trap for those who want to move the swap into a separate method.
Writing the swap as static void swap(int x, int y) { int tmp = x; x = y; y = tmp; } and calling swap(arr[i], arr[minIdx]). Only copies of the elements go to the method; the method changes the copies and the array stays the same. The working version takes the array itself and the two indices: swap(int[] d, int i, int j). This method exchanges d[i] and d[j], and the change is visible in the caller's array.
In the example in the slides the array {64, 25, 12, 22, 11} is sorted. If a line that prints Arrays.toString(arr) at the end of each pass is added to selectionSort, the passes become visible:
int[] arr = {64, 25, 12, 22, 11};
selectionSort(arr);
// selectionSort prints at the end of every pass:
// System.out.println("i=" + i + ": "
// + Arrays.toString(arr));Pass i | Scanned j | Smallest (index) | Swap | Array at the end of the pass |
|---|---|---|---|---|
| start | — | — | — | [64, 25, 12, 22, 11] |
| 0 | 1…4 | 11 (4) | arr[0] ↔ arr[4] | [11, 25, 12, 22, 64] |
| 1 | 2…4 | 12 (2) | arr[1] ↔ arr[2] | [11, 12, 25, 22, 64] |
| 2 | 3…4 | 22 (3) | arr[2] ↔ arr[3] | [11, 12, 22, 25, 64] |
| 3 | 4…4 | 25 (3) | with itself | [11, 12, 22, 25, 64] |
i = 0: the inner loop looks for the smallest value and finds 11 (index 4). (b) After the swap the first cell is in its final place. (c) i = 1: the smallest is 12 (index 2). (d) After four passes the array is sorted.On the last pass the smallest element is already in place and is swapped with itself; the array does not change. The code does not check for this case separately. An if (minIdx != i) condition could avoid the needless swap, but it does not change the cost of the algorithm.
The number of comparisons is independent of the order of the input. In the first pass the inner loop looks at n − 1 elements, in the second at n − 2; in the last pass it looks at a single element. The total:
(n − 1) + (n − 2) + … + 1 = n(n − 1) / 2
For an array of 5 elements, 4 + 3 + 2 + 1 = 10 comparisons are made. For n = 1000 it is 499,500. Even if the array is already sorted, the inner loop runs to the end on every pass; this is why selection sort is O(n²) in every case. The number of swaps, however, is at most n − 1. In situations where a swap is expensive this is an advantage.
3.3.5.7Bubble sort
Bubble sort is a sorting method that compares two neighboring elements of the array and exchanges them if they are in the wrong order. On each pass the largest element of the remaining part rises toward the end “like a bubble”.
static void bubbleSort(int[] arr) {
int n = arr.length;
for (int pass = 0; pass < n - 1; pass++) {
boolean swapped = false;
for (int j = 0; j < n - 1 - pass; j++) {
if (arr[j] > arr[j + 1]) { // wrong order
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
swapped = true;
}
}
System.out.println(Arrays.toString(arr));
if (!swapped) break; // no swap: sorted
}
}For the array {64, 25, 12, 22, 11, 36, 48} the array looks like this at the end of each pass:
[25, 12, 22, 11, 36, 48, 64]
[12, 22, 11, 25, 36, 48, 64]
[12, 11, 22, 25, 36, 48, 64]
[11, 12, 22, 25, 36, 48, 64]
[11, 12, 22, 25, 36, 48, 64]The inner loop starts j at 0 and compares arr[j] with arr[j + 1]. If the left one is larger, a swap is made. When the first pass is over, the largest element, 64, is at the far right; the first line of the output shows this. In the second pass the largest of the remaining six elements, 48, settles in the second cell from the right; but since 36 and 48 are already in place, this pass does not change them.
After each pass one more element at the end settles in its final place. That is why the bound of the inner loop is n - 1 - pass: no comparisons are made again with the elements already in place. j + 1 must also stay inside the array. If the bound were written n - pass, j would be 6 on the first pass and an attempt would be made to access arr[7].
The swapped flag is the clever part of the algorithm. If no swap was made in a pass, all neighboring pairs are in the right order, that is, the array is sorted. In the example the array is sorted after the fourth pass. The fifth pass makes no swap and the loop is left with break; there is no need for a sixth pass. This is why the last two lines of the output are the same.
| Pass | Comparison | Settled | Array at the end of the pass |
|---|---|---|---|
| 0 | 6 | 64 | [25, 12, 22, 11, 36, 48, 64] |
| 1 | 5 | 48 | [12, 22, 11, 25, 36, 48, 64] |
| 2 | 4 | 36 | [12, 11, 22, 25, 36, 48, 64] |
| 3 | 3 | 25 | [11, 12, 22, 25, 36, 48, 64] |
| 4 | 2 | no swap: break | [11, 12, 22, 25, 36, 48, 64] |
In this run a total of 6 + 5 + 4 + 3 + 2 = 20 comparisons and 11 swaps are made. If the array were sorted from the start, no swap would occur in the first pass and the loop would end after one pass: n − 1 comparisons, that is, O(n). In the worst case, when the array is in reverse order, all the passes run and the number of comparisons is again n(n − 1)/2; O(n²). The difference from selection sort is that the number of swaps can also be O(n²). In a reverse-ordered array every comparison ends with a swap.
In how many passes and with how many comparisons is the array {2, 1, 3, 4, 5} sorted by bubble sort?
In the first pass 2 and 1 are swapped and there are no swaps in the next three comparisons: 4 comparisons, array [1, 2, 3, 4, 5]. Because swapped is true, the second pass begins. In the second pass 3 comparisons are made, no swap occurs and break runs.
Result: 2 passes, 4 + 3 = 7 comparisons. Selection sort would make 10 comparisons for the same array.
3.3.5.8Reversing an array
The easy but wasteful way to reverse an array is to open a second array of the same size and copy the elements into it from the end to the start. A better way is to reverse the array in place:
static void reverse(int[] arr) {
int left = 0;
int right = arr.length - 1;
while (left < right) {
// Swap the start and end elements
int tmp = arr[left];
arr[left] = arr[right];
arr[right] = tmp;
// Increase the start index, decrease the end index
left++;
right--;
}
}[1, 2, 3, 4, 5]
→ [5, 4, 3, 2, 1]
[1, 2, 3, 4]
→ [4, 3, 2, 1]left comes from the left and right from the right; on each pass the two elements at the ends are swapped. In an array of odd length the middle element stays in place.This method is called the two-pointer technique. left starts at 0 and right at the last index. On each pass the elements at the two ends are swapped, and then the pointers come one step closer to each other. When the condition left < right turns false, that is, when the pointers meet or pass each other, the job is done.
left | right | Condition | tmp | Array |
|---|---|---|---|---|
| 0 | 4 | 0 < 4 true | 1 | [5, 2, 3, 4, 1] |
| 1 | 3 | 1 < 3 true | 2 | [5, 4, 3, 2, 1] |
| 2 | 2 | 2 < 2 false | — | the loop ends |
reverse. (a) The pointers at the ends. (b) arr[0] and arr[4] have been swapped. (c) arr[1] and arr[3] have been swapped. (d) left = right = 2: the loop ends and the 3 in the middle stays in place.Two swaps are enough for an array of five elements. In an array of four elements two swaps are made as well: first 0 with 3, then 1 with 2; then left becomes 2 and right becomes 1 and the condition turns false. In general n/2 swaps (with integer division) are needed. Each swap is three assignments and the amount of work is proportional to n: O(n). Since no extra array is needed, the extra memory is O(1). Algorithms that work like this are called in-place algorithms.
The method is void and returns nothing. Even so, the caller's array changes, because the reference to the array came into the method. The line → [5, 4, 3, 2, 1] in the output is produced by main printing its own array after the method call.
Running the reversal loop over the whole array: swapping d[i] and d[d.length - 1 - i] with for (int i = 0; i < d.length; i++). In the first half the array is reversed; in the second half the same pairs are swapped again and the array returns to its old state. For {1, 2, 3, 4, 5} the result is again [1, 2, 3, 4, 5]. The loop must go over only half the array: i < d.length / 2.
3.3.6Multidimensional arrays
Some data is naturally in the form of a table: the grades of a class by course, the admittance matrix of a circuit, the pixel grid of a picture. It is possible to keep such data in a one-dimensional array, but the row and column information then has to be managed by hand with index arithmetic. Multidimensional arrays leave this job to the language. Java supports arrays of two or more dimensions.
3.3.6.1Two-dimensional arrays
A two-dimensional array is a table-like array whose elements are arranged in rows and columns. An element is accessed with matrix[row][col]: the first index gives the row and the second gives the column.
int[][] matrix = new int[3][3]; // a matrix of size 3x3
matrix[1][2] = 6; // row 2, column 3matrix[1][2] = 6 writes to the third column of the second row.new int[3][3] creates a matrix of 3 rows and 3 columns. As with one-dimensional arrays, all cells start with the default value, here 0. The line matrix[1][2] = 6 writes to the third column of the second row. Because indices again start at 0, “row 2” corresponds to index 1 and “column 3” to index 2.
The order of row and column is a convention, but it must be consistent. In Java the first index selects the outer array and the second selects the inner array. In matrices this means that the first index is the row; it also agrees with the mathematical notation aij. In images the [y][x] order is used for the same reason: first the row (height), then the column (width).
3.3.6.2Arrays of arrays
Two-dimensional arrays can also be given initial values with an initializer list. This time each row is written inside its own braces:
int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
System.out.println(matrix.length + " "
+ matrix[0].length + " " + matrix[1][2]);3 3 6To understand the output, you need to know how Java builds a two-dimensional array. In Java there is no real “table”. A 2D array is actually an array of arrays. matrix is an array of three elements, and each element is a reference to an int[], that is, to a row.
matrix is an array of row arrays. The three cells of the outer array point to three separate row arrays on the heap. matrix[1] is the second row itself.Figure 3.3.24 shows this structure. matrix.length is the length of the outer array, that is, the number of rows: 3. matrix[0] is the first row itself and is an int[]; matrix[0].length is the number of columns of the first row: 3. matrix[1][2] first selects the second row and then reads the third element of that row: 6.
This structure has practical consequences. matrix[1] is a meaningful expression on its own and gives a row as a one-dimensional array. Arrays.toString(matrix[1]) prints [4, 5, 6]. A row can be passed directly to a method that expects a one-dimensional array. On the other hand, Arrays.toString(matrix) prints not the contents of the rows but their identifiers: [[I@…, [I@…, [I@…]. To print nested arrays, Arrays.deepToString is used.
Find the trace of the matrix int[][] m = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};, that is, the sum of its diagonal elements.
On the diagonal the row and column indices are equal: m[0][0], m[1][1], m[2][2]. So a single loop is enough: for (int i = 0; i < m.length; i++) trace += m[i][i];.
The passes make trace 1, 6 and 15. The trace of the matrix is 1 + 5 + 9 = 15. The trace is defined only for a square matrix; in a non-square matrix m[i][i] may go outside a row.
3.3.6.3Jagged arrays and Pascal's triangle
Because the rows are separate arrays, their lengths do not have to be equal. A multidimensional array whose rows have different lengths is called a jagged array.
int[][] triangle = new int[3][];
for (int i = 0; i < triangle.length; i++) {
triangle[i] = new int[i + 1];
}
System.out.println(triangle[0].length + " " + triangle[1].length
+ " " + triangle[2].length);
int[][] table = {{1, 2}, {3, 4, 5}};
for (int[] row : table) {
for (int x : row) {
System.out.print(x + " ");
}
System.out.println();
}1 2 3
1 2
3 4 5 triangle are 1, 2 and 3.new int[3][] gives only the first dimension. Three row references are created, but the rows themselves are not; all three references are null. The rows are allocated one by one in a loop: triangle[i] = new int[i + 1]. In the end the row lengths are 1, 2 and 3. If a row is accessed before it is allocated, a NullPointerException occurs. The second dimension alone cannot be given: new int[][3] does not compile.
The second part of the program builds a jagged array with an initializer list: the first row of table has two elements and the second has three. When traversing with for-each, the element of the outer loop is an int[] row; the inner loop goes over the elements of that row. In jagged arrays the bound of the inner loop must be separate for each row. When writing with a classic for, matrix[i].length is therefore used. Writing a fixed number of columns causes an out-of-bounds error on the short rows.
A nice application of a jagged array is Pascal's triangle. Each row of the triangle is one element longer than the previous one. The two ends of a row are 1; the inner elements are the sum of the two elements standing immediately to the left and immediately above in the row above.
int[][] p = new int[4][];
for (int i = 0; i < p.length; i++) {
p[i] = new int[i + 1];
p[i][0] = 1;
p[i][i] = 1;
for (int j = 1; j < i; j++) {
p[i][j] = p[i - 1][j - 1] + p[i - 1][j];
}
}
System.out.println(Arrays.toString(p[3]));The program prints [1, 3, 3, 1]. This row holds the coefficients of the expansion of (a + b)³.
i | Creating the row | Ends | Inner cells (j = 1 … i − 1) | p[i] |
|---|---|---|---|---|
| 0 | new int[1] | p[0][0] = 1 (both ends are the same cell) | none | [1] |
| 1 | new int[2] | p[1][0] = p[1][1] = 1 | none (j < 1 is false at once) | [1, 1] |
| 2 | new int[3] | 1, 1 | p[2][1] = 1 + 1 = 2 | [1, 2, 1] |
| 3 | new int[4] | 1, 1 | p[3][1] = 1 + 2 = 3, p[3][2] = 2 + 1 = 3 | [1, 3, 3, 1] |
new int[4][] sets aside only four row references; all are null. (b) When the loop ends the row lengths are 1, 2, 3 and 4.The subtle part of the code is the bounds of the inner loop. j starts at 1 and continues while it stays less than i; this way the end cells are not touched. In the rows i = 0 and i = 1 there are no inner cells and the inner loop never runs. The expression p[i - 1][j] is also safe: since j is at most i − 1, it does not pass the last index of the previous row. Row i has i + 1 elements; the total number of elements is 1 + 2 + … + n = n(n + 1)/2. Using a jagged array instead of a square matrix saves roughly half the memory.
3.3.6.4Filling and printing a matrix
The general way to traverse a two-dimensional array is two nested loops. The outer loop goes over the rows and the inner loop over the columns of a row.
public class MultiDimExample {
public static void main(String[] args) {
// a two-dimensional array (matrix) of size 3x3
int[][] matrix = new int[3][3];
// Assigning initial values to the elements of the matrix
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
matrix[row][col] = row * 3 + col + 1;
}
}
// Printing the matrix to the screen
System.out.println("Matrix contents:");
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println(); // Moving to a new line
}
}
}Matrix contents:
1 2 3
4 5 6
7 8 9 In the filling loop row * 3 + col + 1 is written to each cell. This expression numbers the cells row by row from 1 to 9. row * 3 is the number of cells in the earlier rows; there are three cells in each row. col adds the position within the row. + 1 makes the numbering start from 1 rather than 0.
row | col = 0 | col = 1 | col = 2 |
|---|---|---|---|
| 0 | 0 + 0 + 1 = 1 | 0 + 1 + 1 = 2 | 0 + 2 + 1 = 3 |
| 1 | 3 + 0 + 1 = 4 | 3 + 1 + 1 = 5 | 3 + 2 + 1 = 6 |
| 2 | 6 + 0 + 1 = 7 | 6 + 1 + 1 = 8 | 6 + 2 + 1 = 9 |
new int[3][3]: all cells 0. (b) The first row is filled: 1, 2, 3. (c) The second row is filled. (d) The last cell matrix[2][2] = 9.The cells are filled row by row: first [0][0], [0][1], [0][2]; then the inner loop ends and the outer loop moves on to the next row. This order is called row-major traversal. The printing loop goes through in the same order. The elements of each row are written side by side with print; when the inner loop ends, the println() in the outer loop moves to the next line. If println() were moved inside the inner loop, each number would be written on a separate line.
The cost of nested loops is the product of the number of rows and the number of columns. Traversing an r × c matrix takes r · c steps. For a square n × n matrix this is O(n²). The matrix itself holds n² elements; there is no cheaper way to touch each element once.
Let the sum of each row of the matrix int[][] m = {{1, 2, 3}, {4, 5, 6}}; be written into an array.
The result array needs as many cells as there are rows: int[] t = new int[m.length];. In the nested loop t[i] += m[i][j]; is written. The bound of the inner loop is m[i].length.
The sum of the first row is 1 + 2 + 3 = 6 and of the second 4 + 5 + 6 = 15. The result is t = [6, 15]. The sum of two matrices is computed with the same method: c[i][j] = a[i][j] + b[i][j]. The sum of {{1, 2}, {3, 4}} and {{5, 6}, {7, 8}} is [[6, 8], [10, 12]].
3.3.6.5Three and more dimensions
Arrays of three or more dimensions can be used in Java as well. Each extra dimension means one more pair of square brackets. A three-dimensional array is an array of two-dimensional arrays.
// a three-dimensional array of size 3x3x3
int[][][] arr3d = new int[3][3][3];
arr3d[1][2][0] = 16; // layer 1, row 2, column 0arr3d[1][2][0] is the first cell of the third row of the second layer.More dimensions allow more complex data. The rooms of a building can be kept as [floor][row][col], a color image as [y][x][channel], a table of measurements that change over time as [time][row][col]. The number of elements is the product of the dimensions: new int[3][3][3] holds 3 × 3 × 3 = 27 cells. As the number of dimensions grows, memory grows quickly. A color image of 1920 × 1080 kept as int[1080][1920][3] needs 6,220,800 cells, about 25 MB.
int[][][] arr3d = new int[3][3][3];
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
for (int z = 0; z < 3; z++) {
arr3d[x][y][z] = x * 9 + y * 3 + z + 1;
}
}
}
System.out.println("3D array contents:");
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
for (int z = 0; z < 3; z++) {
System.out.print(arr3d[x][y][z] + " ");
}
System.out.println();
}
System.out.println();
}3D array contents:
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
19 20 21
22 23 24
25 26 27 Three nested loops traverse the array. The innermost z goes over the columns of a row, the middle y over the rows of a layer, and the outermost x over the layers. x * 9 + y * 3 + z + 1 is written to each cell. 9 is the number of cells in a layer; the formula is the matrix-filling pattern row * 3 + col + 1 extended by one dimension. As a result the cells are numbered from 1 to 27. arr3d[1][2][0] = 1 · 9 + 2 · 3 + 0 + 1 = 16. After each layer, the println() in the outer loop prints an empty line and the layers are separated from each other in the output.
3.3.6.6Matrix transpose
The transpose T of a matrix M is the matrix in which rows have become columns and columns have become rows: T[j][i] = M[i][j]. The transpose of an r × c matrix is c × r.
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println("Original matrix:");
printMatrix(matrix);
int rows = matrix.length;
int cols = matrix[0].length;
int[][] transposed = new int[cols][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
transposed[j][i] = matrix[i][j];
}
}
System.out.println("Transposed matrix:");
printMatrix(transposed);
}Original matrix:
1 2 3
4 5 6
Transposed matrix:
1 4
2 5
3 6 The program first reads the dimensions from the array: rows = matrix.length = 2, cols = matrix[0].length = 3. For the transpose a new array is needed, and its dimensions are in reverse order: new int[cols][rows], that is, 3 × 2. A non-square matrix cannot be transposed in place, because the result has a different shape.
i | j | Read | Written |
|---|---|---|---|
| 0 | 0 | matrix[0][0] = 1 | transposed[0][0] |
| 0 | 1 | matrix[0][1] = 2 | transposed[1][0] |
| 0 | 2 | matrix[0][2] = 3 | transposed[2][0] |
| 1 | 0 | matrix[1][0] = 4 | transposed[0][1] |
| 1 | 1 | matrix[1][1] = 5 | transposed[1][1] |
| 1 | 2 | matrix[1][2] = 6 | transposed[2][1] |
matrix and the 3×2 transposed filled with 0s. (b) The first row of matrix has become the first column of the transpose. (c) The last copy: matrix[1][2] = 6 is written to transposed[2][1].The loops go through the original matrix row by row. Each element is written to the cell of the transpose with its indices swapped. Table 3.3.18 shows this swap: when i = 0, the first row of matrix is read and written to the first column of transposed. The diagonal cell [1][1] stays in place. The amount of work is proportional to the number of elements: r · c copies.
Creating the transpose array with the same dimensions as the original matrix: new int[rows][cols]. For a 2×3 matrix this means a 2×3 array. When a write to transposed[2][0] is attempted, the row index 2 is out of bounds and an ArrayIndexOutOfBoundsException occurs. With square matrices this error is invisible; the code reveals it only when tried with a non-square matrix.
3.3.6.7A helper method: printMatrix
The transpose program prints the matrix twice: first the original matrix and then the transpose. Instead of writing the printing code twice, the job has been moved into a helper method:
public static void printMatrix(int[][] matrix) {
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();
}
}The parameter of the method is int[][] matrix, and it works with a two-dimensional array of any dimensions. The reason is that the number of rows is read from matrix.length and the number of columns from matrix[i].length, that is, from the array. The same method prints both the 2×3 original matrix and the 3×2 transpose correctly. Given a jagged array, it would print that correctly too.
What goes to the method is not a copy of the array but its reference. So the call is cheap even for a large matrix: only an address is copied. Because the method does not change the array, passing a copy of the reference has no side effect either.
What would happen if the bounds were written as constants? A printing method whose loops are written with i < 3 and j < 3, when applied to the 3×2 transposed matrix, tries to access the third element of the first row:
0 0 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
at TransposeFixed.print(TransposeFixed.java:9)
at TransposeFixed.main(TransposeFixed.java:4)After two 0s are printed, the exception occurs. The stack trace has two lines: the error is on line 9 of the print method, and this method was called from line 4 of main. A stack trace is read from the innermost call outward. Using length instead of a fixed number makes the method work correctly with any dimensions.
3.3.7Application: Tic Tac Toe
This section combines what has been learned about arrays in a single program: a two-dimensional array, nested loops, passing an array to a method, input from the user and bounds checking. The program is the game of Tic Tac Toe (X-O), played by two people on the same computer.
3.3.7.1The game and its data structure
The game is played on a 3×3 board. Two players, X and O, take turns putting their own mark in an empty cell. The one who places three of their marks in the same row, the same column or the same diagonal wins the game. If no empty cell remains and nobody has won, the game ends in a draw.
The most natural data structure for the board is char[][] board = new char[3][3];. Each cell holds one character: 'X', 'O' or ' ' for an empty cell. A move is a single assignment: board[row][col] = player. The whole state of the game consists of the board and the information about whose turn it is.
3.3.7.2main and splitting into methods
import java.util.Scanner;
public class TicTacToe {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
char[][] board = new char[3][3]; // 3x3 board
char player = 'X'; // the first player is X
boolean running = true;
initBoard(board); // all cells empty
while (running) {
printBoard(board);
makeMove(board, player);
running = isRunning(board, player);
// switch players
player = (player == 'X') ? 'O' : 'X';
}
printBoard(board);
}
// ... methods
}main is short and readable, because the job is split into four methods: filling the board, showing it, taking a move, and checking whether the game goes on. The loop repeats these steps as long as running is true. At the end of each turn play passes to the other player. (player == 'X') ? 'O' : 'X' is the conditional operator: it gives O if the player is X, and X otherwise.
A copy of the reference to the board goes to the methods. When makeMove writes to a cell of the board, the change is visible in the board in main, because there is only one array. This is the useful side of arrays being reference types: methods can change shared state.
The Scanner object is declared as a static field at the top of the class. This way all the methods use the same Scanner. The methods themselves are static too. Since main is static, the methods it calls without creating an object must be static as well. If the word static is forgotten, the compiler gives this message:
E_Static.java:4: error: non-static method initBoard(char[][]) cannot be referenced from a static context
initBoard(board);
^
1 error3.3.7.3Filling and showing the board
public static void initBoard(char[][] board) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = ' ';
}
}
}
public static void printBoard(char[][] board) {
System.out.println("-------------");
for (int i = 0; i < 3; i++) {
System.out.print("| ");
for (int j = 0; j < 3; j++) {
System.out.print(board[i][j] + " | ");
}
System.out.println("\n-------------");
}
}The empty board looks like this:
-------------
| | | |
-------------
| | | |
-------------
| | | |
-------------The cells of a board created with new char[3][3] start with '\u0000'. This character is invisible on the screen, or appears as a strange symbol in some terminals. Also, the check for an empty cell will compare against ' '. That is why initBoard first writes the space character to all the cells.
printBoard prints each row in the form | X | O | |. At the start of the row "| " is printed, and after each cell " | ". The string "\n-------------" at the end of the row does two jobs with a single println: \n ends the row, then the separator line follows, and println moves to the next line.
3.3.7.4Taking a move
static Scanner scanner = new Scanner(System.in);
public static void makeMove(char[][] board, char player) {
int row, col;
do {
System.out.print("Player " + player
+ " 's turn. Enter row and column (1-3): ");
row = scanner.nextInt() - 1;
col = scanner.nextInt() - 1;
} while (row < 0 || row > 2 || col < 0 || col > 2
|| board[row][col] != ' ');
board[row][col] = player;
}The user enters the row and column between 1 and 3, because people count from 1. The code turns these values into indices 0–2 with - 1. The input is taken with a do-while loop. do-while runs the body at least once and checks the condition at the end. The question is asked first; if an invalid or occupied cell was chosen, the condition is true and the question is asked again.
The order in the condition is deliberate. The four bounds checks come first, and the cell check is written last. The || operator does short-circuit evaluation: it goes from left to right and stops at the first true condition. If the user enters 4 5, row becomes 3 and col becomes 4. row > 2 is true and evaluation stops there. board[3][4] is never read, no exception occurs, and the question is asked again. If the cell check had been written before the bounds checks, the program would have crashed with an ArrayIndexOutOfBoundsException.
Writing the condition in the order board[row][col] != ' ' || row < 0 || …. Short-circuiting works only from left to right; since the access to the cell is at the far left, it is made before the bounds checks. With valid input the program runs without trouble, and the bug shows up only when the user enters a number outside the range. That is why boundary values (0, 4, −1) must be tried separately in testing.
3.3.7.5Winner and draw
After each move the game answers two questions: is there a winner, and is there an empty cell left? The isRunning method first checks for a win:
public static boolean isRunning(char[][] board, char player) {
// Check the winning cases
if ((board[0][0] == player && board[0][1] == player && board[0][2] == player) ||
(board[1][0] == player && board[1][1] == player && board[1][2] == player) ||
(board[2][0] == player && board[2][1] == player && board[2][2] == player) ||
(board[0][0] == player && board[1][0] == player && board[2][0] == player) ||
(board[0][1] == player && board[1][1] == player && board[2][1] == player) ||
(board[0][2] == player && board[1][2] == player && board[2][2] == player) ||
(board[0][0] == player && board[1][1] == player && board[2][2] == player) ||
(board[0][2] == player && board[1][1] == player && board[2][0] == player)) {
System.out.println("Congratulations, player " + player + " wins!");
return false;
}
// ... draw checkThe eight winning lines are checked one by one. Each line requires all three cells to hold the player's mark; these conditions are joined with &&. One line is enough; the lines are joined with ||. Only the player who made the last move is checked. Only that player can have completed a new line; if the other player had won, the game would have ended on the previous move.
If there is a winner, the method returns false. This looks backwards at first sight, but the name of the method is the question “is the game still going?” and the answer is “no”. The long conditional expression could also have been written with loops: one loop for the three rows and three columns, and a separate check for the two diagonals. The explicit form is long, but it shows directly which lines are checked.
If there is no winner, a draw is checked for:
// the rest of the isRunning method
// Check for a draw
boolean draw = true;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == ' ') {
draw = false;
break;
}
}
if (!draw) {
break;
}
}
if (draw) {
System.out.println("The game is a draw.");
return false;
}
return true;This code starts with an assumption: the game has ended in a draw (draw = true). A single empty cell refutes this assumption. When the inner loop finds an empty cell, it sets draw to false and leaves with break. break leaves only the loop it is in. The outer loop keeps running. That is why a second check is needed in the body of the outer loop: if (!draw) break;.
The order of the checks matters too. A win is checked first, then a draw. The last move may fill the board and complete a line at the same time. If the order were reversed, such a game would wrongly be declared a draw.
To see how the two breaks work, let us trace only the draw code with a board that has a single empty cell:
boolean draw = true;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == ' ') {
draw = false;
break;
}
}
if (!draw) {
break;
}
}
System.out.println(draw ? "draw" : "continue");i | j | board[i][j] | Operation | draw |
|---|---|---|---|---|
| 0 | 0 | 'X' | not empty | true |
| 0 | 1 | 'O' | not empty | true |
| 0 | 2 | 'X' | the inner loop ends by itself; !draw is false | true |
| 1 | 0 | 'O' | not empty | true |
| 1 | 1 | 'X' | not empty | true |
| 1 | 2 | ' ' | empty cell: draw = false, inner break | false |
| 1 | — | — | !draw is true: outer break | false |
(1, 2). (b) Outer break: row 2 is never checked.The program prints continue. Of the nine cells only six were looked at; row 2 is never checked. Once an empty cell has been found, continuing the search is pointless, because the result can no longer change. This kind of “stop at the first counterexample” pattern is the two-dimensional counterpart of the break in linear search.
3.3.7.6A sample game
Let a game be played with the following inputs. Each pair is the row and column choice of the player whose turn it is:
1 1 1 2 2 2 2 2 1 3 3 3| Player | Input | Assignment | Result |
|---|---|---|---|
| X | 1 1 | board[0][0] = 'X' | no winner, empty cells remain; play passes to O |
| O | 1 2 | board[0][1] = 'O' | play passes to X |
| X | 2 2 | board[1][1] = 'X' | play passes to O |
| O | 2 2 | — | board[1][1] is occupied: the question is asked again |
| O | 1 3 | board[0][2] = 'O' | play passes to X |
| X | 3 3 | board[2][2] = 'X' | main diagonal is X: the winning message, the loop ends |
do-while condition is true and the question is asked again. (c) X completes the main diagonal.The final output of the program:
Congratulations, player X wins!
-------------
| X | O | O |
-------------
| | X | |
-------------
| | | X |
-------------In the fourth move the cell chosen by O is occupied. board[1][1] != ' ' is true and do-while asks the same question once more. The turn does not change in the meantime, because makeMove does not return until a valid move has been made. In the last move X completes the main diagonal ([0][0], [1][1], [2][2]). isRunning prints the winning message and returns false. The loop in main ends and the board is shown for the last time.
The program has aspects that could be improved. If the user types a letter instead of a number, nextInt() throws InputMismatchException and the program stops. The draw check could be moved to a separate isBoardFull method; then isRunning would be shorter and each method would answer a single question. The win check could also be narrowed to look at the row, the column and, if necessary, the diagonals of the last move.
3.3.8Common mistakes
Array mistakes fall into two groups. Compile errors show up before the program runs, with the messages given by javac, and are relatively easy to fix. Run-time errors appear while the program runs, as an exception, or produce a wrong result without any message at all. The following two tables bring together the mistakes that were treated separately in the body of the notes. The messages were obtained with the javac and java tools of JDK 21.
| Mistake | Code | javac message | Fix |
|---|---|---|---|
| Giving the short initializer later | a = {1, 2, 3}; | illegal start of expression | a = new int[]{1, 2, 3}; |
| Both size and list | new int[3]{1, 2, 3} | array creation with both dimension expression and initialization is illegal | Give only one of them. |
| Forgetting the size | new int[] | array dimension missing | new int[n] |
| Element of the wrong type | int[] a = {1, 2.5, 3}; | incompatible types: possible lossy conversion from double to int | double[] or integer values |
Writing length() | a.length() | cannot find symbol … method length() | a.length |
| C-style size | int a[3] = {…}; | ']' expected | int[] a = {…}; |
| Variable declared inside a branch | if (…) { double median = …; } | cannot find symbol … variable median | Declare the variable outside the branches. |
Method that is not static | public void initBoard(…) | non-static method … cannot be referenced from a static context | public static void … |
| Mistake | Result | Fix |
|---|---|---|
Thinking the last index is length: a[a.length], i <= a.length | ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 | a[a.length - 1], i < a.length |
An array that was never created: int[] a = null; a[0] | NullPointerException: Cannot load from int array … | The array is first created with new. |
Printing an array directly: println(a) | An identifier such as [I@1c20c684 | Arrays.toString(a) |
Mistaking assignment for copying: b = a | Changing b[0] changes a[0] too. | a.clone(), Arrays.copyOf |
Comparing contents with == | false for two arrays with the same elements | Arrays.equals(a, b) |
| Thinking the first index is 1 | The first element is skipped or the bound is exceeded. | arr[0] in the code; (i + 1) + ". element" on the screen |
Writing to an array with for-each | The array does not change; only the copy does. | Classic for and arr[i] = … |
| Binary search on an unsorted array | Meaningless result, no warning | Arrays.sort first |
| Mean with integer division | 29 / 6 = 4, then 4.0 | sum / (double) n |
Most of these mistakes come down to two sources. The first is that the index starts at 0 and the last index is length − 1. The second is that an array variable holds a reference, not a value. If these two points are checked while array code is written, most mistakes are prevented as it is written. When the code is tried out, the boundary cases must also be tested separately: the empty array, the array with one element, the cases where the target is the first and the last element, odd and even lengths.
3.3.9Summary
- An array is a structure that holds a fixed number of elements of the same type in consecutive cells. Elements are accessed by an index starting at 0; the last index of an array with n elements is n − 1.
- An array is created with
new int[n]and its cells get default values. This value is 0 or 0.0 for numbers,falseforboolean,'\u0000'forchar, andnullfor objects. - The initializer list
{1, 2, 3}is used only on the declaration line; elsewherenew int[]{1, 2, 3}is written. The size and the list cannot be given together. lengthis a property and is written without parentheses. All the indices of an array are traversed with the patternfor (int i = 0; i < arr.length; i++).- The
for-eachloop gives a copy of the next element on each pass. It is suitable for reading; for writing to the array and for jobs that need the index, the classicforis used. - An array variable is a reference.
b = acreates a second name for the same array;clone()andArrays.copyOfcreate a new array.==compares addresses,Arrays.equalscompares contents. - When an array is passed to a method, a copy of the reference goes. If the method changes the cells, the change is visible in the caller; assigning a new array to the parameter does not affect the caller.
- All arrays are on the heap; only references sit on the stack. Unreachable arrays are cleaned up by the garbage collector.
- An out-of-bounds index causes
ArrayIndexOutOfBoundsException. The message gives the faulty index, the length and the line number. - The mean is found in one pass in O(n), the median with the middle element after sorting, and the mode with the longest run in the sorted array. The median and the mode are O(n log n) because of the sorting.
- Access is O(1), binary search O(log n), linear search and reversal O(n), and matching, selection sort and bubble sort O(n²). Binary search works only on a sorted array.
- A multidimensional array is an array of arrays.
m.lengthis the number of rows andm[i].lengthis the number of columns of that row. Rows can have different lengths; that is whym[i].lengthis used in loops. - Tic Tac Toe combines many techniques: a
char[][]board, state shared by reference, input validation withdo-while, bounds checking with short-circuiting, and leaving nested loops with twobreaks.
3.3.10Key terms
- array
- element
- index
- array initializer
- default value
- for-each loop
- reference type
- null reference
- pass by value
- stack (memory)
- heap (memory)
- garbage collector
- dynamic array
- linear search
- binary search
- time complexity (Big-O)
- selection sort
- bubble sort
- two-dimensional array
- jagged array
- short-circuit evaluation
3.3.11Test Yourself
With
int[] d = {3, 8, 1, 9, 4};, what issafter the loopfor (int i = d.length - 1; i >= 0; i -= 2) s += d[i];? (sstarts at 0.)Answer
The loop starts from the last index, 4, and decreases by two:
i= 4, 2, 0. The elements read ared[4]= 4,d[2]= 1 andd[0]= 3. Whenibecomes −2 the condition is false.s= 4 + 1 + 3 = 8. Hadd.lengthbeen written as the start,d[5]would be accessed on the first pass and the exception would occur.What is printed after the following lines?
int[] x = {2, 4, 6}; int[] y = x; int[] z = x.clone(); y[1] = 0; z[2] = 9;followed byArrays.toString(x),x == yandArrays.equals(x, z).Answer
ypoints to the same array asx;y[1] = 0changes this array andx=[2, 0, 6].zis a separate copy;z[2] = 9changes only the copy andz=[2, 4, 9].x == yis true.Arrays.equals(x, z)is false, because the contents now differ.23 is searched for with binary search in the sorted array
{2, 5, 8, 12, 16, 23, 38, 56, 72, 91}. Which middle indices are looked at? How many comparisons are made?Answer
lo= 0,hi= 9 →mid= 4 (16); 23 > 16,lo= 5.mid= (5 + 9) / 2 = 7 (56); 23 < 56,hi= 6.mid= (5 + 6) / 2 = 5 (23): found. The middle indices are 4, 7 and 5. 3 comparisons are made and the method returns 5. If 40 were searched for,mid= 6 (38) in the fourth step, then the space would be empty and −1 would be returned.The array
{5, 1, 4, 2, 8}is sorted with selection sort. What does the array look like at the end of each pass? How many comparisons are made?Answer
i= 0: the smallest is 1 (index 1), swap:[1, 5, 4, 2, 8].i= 1: the smallest is 2 (index 3), swap:[1, 2, 4, 5, 8].i= 2: the smallest, 4, is already in place.i= 3: the smallest, 5, is already in place. The array was sorted after the second pass, but selection sort does not notice. The number of comparisons is 4 + 3 + 2 + 1 = 10 in every case.For
int[][] m = {{1, 2}, {3, 4}, {5, 6}};, what arem.length,m[0].lengthand the sum of the second column?Answer
mis an array with three rows:m.length= 3. The first row has two elements:m[0].length= 2. The index of the second column is 1:m[0][1] + m[1][1] + m[2][1]= 2 + 4 + 6 = 12. The loop is writtenfor (int i = 0; i < m.length; i++) t += m[i][1];; the row changes and the column is fixed.After the lines
int[][] r = new int[3][]; r[0] = new int[]{1}; r[2] = new int[2];, what doesr[2].length + r[1].lengthgive?Answer
It gives no number; the program stops with a
NullPointerException.new int[3][]creates only three row references. Rows have been assigned tor[0]andr[2], butr[1]is stillnull.r[1].lengthtries to read a field of anullreference. The message has the formCannot read the array length because "…[1]" is null.Let
static void f(int[] d) { d = new int[]{9, 9}; }andstatic void g(int[] d) { d[0] = 9; }be given. Withint[] a = {1, 2};, firstf(a)and theng(a)are called. What isaafter each call?Answer
After
f(a),ais still[1, 2]. Thedinfis a copy of the reference; assigning a new array binds only this copy to the new array. Afterg(a),a=[9, 2]. Thedingpoints to the same array andd[0] = 9writes to a cell of that array.The mode algorithm given in the notes is applied to the sorted array
{1, 1, 3, 3, 3, 5, 5, 5}. What is the result? What would change if>=were written instead of>?Answer
When the run of 3s reaches length 3, 3 > 2 is true and the longest run becomes 3 × 3. The run of 5s also reaches 3, but 3 > 3 is false. The result is mode 3, count 3; in a tie the first one found is kept. With
>=the run of 5s would overtake the longest run at equal length and the result would be 5. This set actually has two modes.In how many passes does bubble sort with the
swappedflag finish on the array{2, 1, 3, 4, 5}? How many comparisons would be made without the flag?Answer
In the first pass 2 and 1 are swapped (4 comparisons). In the second pass no swap is made (3 comparisons) and
breakruns: 2 passes, 7 comparisons. Without the flag all the passes would run: 4 + 3 + 2 + 1 = 10 comparisons.
3.3.12Further reading
- Oracle, The Java Tutorials, the pages “Arrays” and “The for Statement”: explain declaring arrays, the initializer list and multidimensional arrays.
java.util.Arraysand the enhancedforare also covered with short examples. It is the official, free starting resource for Java. - A. B. Downey and C. Mayfield, Think Java (2nd ed.), Chapter 7 “Arrays and References”: explains arrays through the concept of a reference. It complements these notes on aliasing, copying and passing an array to a method.
- P. Deitel and H. Deitel, Java: How to Program (11th ed.), Chapter 7 “Arrays and ArrayLists”: a long account with plenty of examples, which also covers the move from arrays to
ArrayList. - J. Gosling et al., The Java Language Specification, Java SE 21 Edition, Chapter 10 “Arrays”: the precise definition of array types, creation, default values and bounds checking. On a point of detail, the last word is in this document.
3.3.13References
- Oracle, The Java Tutorials: “Arrays”; “The for Statement” (enhanced for).
- Oracle, Java SE 21 API Specification:
java.util.Arrays. - J. Gosling et al., The Java Language Specification, Java SE 21 Edition, Oracle, 2023 (Chapter 10: Arrays).
- P. Deitel and H. Deitel, Java: How to Program, 11th ed., Pearson (Chapter 7: Arrays and ArrayLists).
- K. Sierra and B. Bates, Head First Java, 3rd ed., O'Reilly, 2022.
- C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed., Pearson, 2022 (3.10 Arrays).
- A. B. Downey and C. Mayfield, Think Java, 2nd ed., O'Reilly, 2019 (Chapter 7: Arrays and References).
Related pages: Chapter 3.3 slides · Study questions · Glossary · © Sercan Külcü. All rights reserved.