Chapter 3.3: Arrays
Introduction
Learning Outcomes
Explain that an array holds a fixed number of elements of one type in consecutive cells, accessed by an index starting at 0.
Declare one- and multidimensional arrays, create them with new or an initializer list, and traverse them with length.
Predict the effect of assignment, copying and passing to a method, knowing that an array variable holds a reference and that the array itself lives on the heap.
ArrayIndexOutOfBoundsException and common compile errors: recognize them and prevent them with bounds checks.
Write mean, median, mode, linear and binary search, matching, reversal, selection and bubble sort; compare O(1), O(n) and O(n²) costs.
Fill, print and transpose matrices with nested loops, and build Tic Tac Toe with char[][].
The Array Concept
What Is an Array?
- Array: a structure that stores data of the same type in an orderly way under a single name.
- Think of it as one variable that can hold one or more values.
- Elements are accessed by index number; indexing makes access very fast.
- The first index is 0; in an array of n elements the last index is n − 1.
- To access an element, write the array name followed by the index in square brackets:
arr[0].
Example: arr = [10, 20, 30, 40, 50], so arr[0] is the first element, with value 10; arr[4] is the last (50).
The Array Concept
Why Arrays?
Without arrays: 50 variables for 50 students
int grade1 = 70; int grade2 = 85; int grade3 = 90; // ... up to grade50 int sum = grade1 + grade2 + grade3 /* + ... */;
Computing the mean means typing all 50 names; if the class size changes, so does the code.
With an array: one name, a loop does the work
int[] grades = new int[50]; // ... fill grades int sum = 0; for (int i = 0; i < grades.length; i++) { sum += grades[i]; }
The same code works for 5 grades or 5000: the index can be a variable (grades[i]), so the loop visits every element.
grades[i] the cell to read is decided at run time by the value of i.The Array Concept
An Array in Memory
The figure shows a one-dimensional array of five elements. Each element sits in a cell; the cells are laid out side by side (contiguously) in memory.
| index | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| element | 13 | −1 | 4 | 2 | 7 |
a[1] = −1, a[4] = 7, a.length = 5. a[5]: there is no such cell; valid indices are 0…4.
The Array Concept
Pros and Cons
- Stores data in order, contiguously.
- Indexing gives fast access to elements:
arr[i]takes the same time for every i. - Groups related data together; easy to process with loops.
- Lean memory use: only the elements and the length are stored.
- Fixed size: once created, an array cannot be resized.
- To add an element when it is full, you must create a larger new array and copy.
- Inserting into or deleting from the middle requires shifting elements (extra cost).
- Holds elements of one type only.
For lists that change size, Java offers ArrayList; it uses an array internally and grows it when full (java.util collections).
The Array Concept
Kinds of Arrays and Their Uses
int[] gradesint[][] tableint[][][] cubeUses
- The most common data structure in programming; ideal for organizing and processing data.
- Measurements: samples read from a sensor every second, an audio signal (
double[]). - Matrices: circuit analysis, systems of linear equations.
- Images: a grid of pixels (
int[height][width]).
Arrays in Java
Declaring Arrays
Type[] arrayName = new Type[arraySize];int, double, char, String…int.int[] numbers = new int[5]; // 5 ints double[] readings = new double[100]; // 100 doubles String[] names = new String[30]; int n = 12; char[] letters = new char[n]; // size from a variable int arr2[] = new int[3]; // C style: legal, not recommended
| Type | Default value |
|---|---|
int, long… | 0 |
double | 0.0 |
boolean | false |
char | '\u0000' (code 0) |
String and objects | null |
Arrays in Java
Access and length
- Array elements are accessed by index; the index starts at 0.
arr[i]is used both for reading and writing.- The size of an array comes from the
lengthfield: the number of elements it holds. lengthis not a method: no parentheses (String'slength()is a method).- In a non-empty array the last element is
arr[arr.length - 1].
int[] numbers = {10, 20, 30, 40, 50}; int first = numbers[0]; // first element int second = numbers[1]; // second element int size = numbers.length; // 5 System.out.println(first + " " + second + " " + size); numbers[1] = 25; // write int last = numbers[numbers.length - 1]; // 50
Output
10 20 5
Arrays in Java
Initializing Arrays
- When an array is declared, its elements can be given initial values with an initializer list (array initializer).
- The size is then not given; the initializers determine it: 5 values make a 5-element array.
int[] numbers = {10, 20, 30, 40, 50}; // 5 elements int[] n = {1, 2, 3, 4, 5}; // 5 values, so n has 5 elements int[] m = new int[]{1, 2, 3}; // long form: works anywhere String[] days = {"Mon", "Tue", "Wed"}; char[] vowels = {'a', 'e', 'i', 'o', 'u'};
a = {1, 2, 3}; (illegal start of expression). Write a = new int[]{1, 2, 3}; instead.new int[3]{1, 2, 3} does not compile: give either a size or a list.Arrays in Java
Example: ArrayExample
public class ArrayExample { public static void main(String[] args) { // declare an array of 5 ints int[] numbers = new int[5]; // assign values to the elements numbers[0] = 10; numbers[1] = 20; numbers[2] = 30; numbers[3] = 40; numbers[4] = 50; // access elements System.out.println("first element: " + numbers[0]); System.out.println("third element: " + numbers[2]); // print all elements in a loop System.out.print("Elements: "); for (int i = 0; i < numbers.length; i++) { System.out.print(numbers[i] + " "); } } }
Output
first element: 10 third element: 30 Elements: 10 20 30 40 50
for (int i = 0; i < arr.length; i++) visits every index of the array, from 0 to length − 1. <= in its place is a common mistake.Arrays in Java · Step-by-step code trace
ArrayExample: Trace the Code Step by Step
new int[5] creates a 5-cell array on the heap; every cell starts at the default value 0. numbers holds this array's reference.
numbers[0] = 10; → writes cell 1 (index 0).
numbers[1] = 20; → writes cell 2 (index 1).
numbers[2] = 30; → writes cell 3 (index 2).
numbers[3] = 40; → writes cell 4 (index 3).
numbers[4] = 50; → writes cell 5 (index 4).
The first element has index 0: numbers[0] is read → 10.
The third element is numbers[2] (index = position − 1) → 30.
print does not end the line; the elements go on one line.
i = 0: 0 < 5 true → numbers[0] = 10 is printed.
i = 1: 1 < 5 true → numbers[1] = 20 is printed.
i = 2: 2 < 5 true → numbers[2] = 30 is printed.
i = 3: 3 < 5 true → numbers[3] = 40 is printed.
i = 4: 4 < 5 true → numbers[4] = 50 is printed.
i = 5: 5 < numbers.length is false → the loop ends. The last valid index is length − 1 = 4.
int[] numbers = new int[5]; numbers[0] = 10; numbers[1] = 20; numbers[2] = 30; numbers[3] = 40; numbers[4] = 50; System.out.println("first element: " + numbers[0]); System.out.println("third element: " + numbers[2]); System.out.print("Elements: "); for (int i = 0; i < numbers.length; i++) { System.out.print(numbers[i] + " "); }
Arrays in Java
The for-each Loop
int[] grades = {70, 85, 90}; // classic for: we have the index for (int i = 0; i < grades.length; i++) { System.out.println("grade " + i + ": " + grades[i]); } // for-each: values only int sum = 0; for (int g : grades) { sum += g; } System.out.println("Sum: " + sum);
Output
grade 0: 70 grade 1: 85 grade 2: 90 Sum: 245
- Enhanced for (for-each):
for (type item : arr)puts the next element intoitemon each pass. - No index is written, so it cannot go out of bounds.
- Only for reading:
g = 0;changes only the copy, not the element in the array. - If you need the index (to write, report a position, compare neighbors), use a classic
for.
Arrays in Java · Step-by-step code trace
for-each: You Get the Value, Not the Cell
A three-cell array lives on the heap; scores holds its reference.
sum starts at 0.
First pass: the loop takes scores[0] and puts a copy of it into p, so p = 60. No index is written.
sum += p → 60.
Second pass: p = 75 (the loop supplies the next element itself).
sum = 60 + 75 = 135.
Last pass: p = 95.
sum = 230. No elements left; the loop ends.
Sum: 230 is printed.
Second loop: p is again a copy of scores[0], 60.
p = 0 changes only the copy; the 60 in the array stays put. The remaining passes are the same.
60 95: the array never changed. for-each cannot write to the array; writing needs a classic for and scores[i].
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]);
Arrays in Java
Temperature Conversion: Arrays and for-each
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 K
double[] celsiusValues = {…};gathers four values into an array.- for-each loop:
for (double celsius : celsiusValues)means “for each element in the array”;celsiustakes the next element on each pass. - The body runs 4 times; the table is produced in one go.
233.14999999999998: floating-point numbers cannot be stored exactly in binary, so small rounding errors appear. When printing,printfcan limit the digits.
Arrays in Java · Step-by-step code trace
A Temperature Table with for-each
The array holds four Celsius values (indices 0–3). The for-each loop will copy them, one by one, into celsius.
The next element (index 0) is copied into celsius: celsius = -40.0.
-40.0 × 1.8 + 32 = -40.0 °F, -40.0 + 273.15 = 233.14999999999998 K. In Kelvin, 233.14999999999998: binary floating point stores the value only approximately.
The line is printed; the body ends and the loop moves to the next element.
The next element (index 1) is copied into celsius: celsius = 0.0.
0.0 × 1.8 + 32 = 32.0 °F, 0.0 + 273.15 = 273.15 K.
The line is printed; the body ends and the loop moves to the next element.
The next element (index 2) is copied into celsius: celsius = 25.0.
25.0 × 1.8 + 32 = 77.0 °F, 25.0 + 273.15 = 298.15 K.
The line is printed; the body ends and the loop moves to the next element.
The next element (index 3) is copied into celsius: celsius = 100.0.
100.0 × 1.8 + 32 = 212.0 °F, 100.0 + 273.15 = 373.15 K.
The last line is printed.
No elements left: the loop ends. The body ran 4 times; no index variable was ever written.
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"); }
Arrays in Java · Step-by-step code trace
An Array Variable Is a Reference
An array is created on the heap; the variable a holds not the array itself but its address (reference).
b = a only copies the address. Now both variables refer to the same array (aliasing).
b[0] = 99 changes the shared array…
…so a[0] also becomes 99.
clone() creates a new array on the heap and copies the elements; c refers to this new array.
c[1] = 77 changes only the copy; the original is unaffected.
a[1] is still 2, while c[1] is 77.
== compares references (addresses): a == b is true (same array), a == c is false (different arrays).
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);
Arrays in Java
The java.util.Arrays Class
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));
Output
[5, 3, 8, 1] [1, 3, 5, 8] [1, 3, 5, 8, 0, 0] [7, 7, 7, 7] false true 2
Method (import java.util.Arrays;) | Purpose |
|---|---|
Arrays.toString(d) | Array as text; println(d) prints an identity like [I@7ef20235 |
Arrays.sort(d) · binarySearch | Sorts in place · finds an index in a sorted array (5 → 2); arrays have no indexOf |
Arrays.copyOf(d, n) · d.clone() | Copies into a new array; extra cells are 0 |
Arrays.fill · Arrays.equals | Same value in every cell · compares contents (== compares addresses) |
Memory and Errors
Where Do Arrays Live in Memory?
String[] plates = {"", "Adana", "Adıyaman", "Afyon"};
System.out.println(plates[1]);
int[] dynamicArr = new int[10]; // allocated on the heap
System.out.println(dynamicArr.length);
dynamicArr = null; // reference dropped
System.out.println(dynamicArr == null);- In C/C++,
int a[10];is on the stack; a raw array frommalloc/new[]is freed by hand withfree/delete[](C++'sstd::vectordoes it for you). - Output:
Adana,10,true. - In Java, all arrays are on the heap; the size can be set at run time, then stays fixed. Freeing is automatic.
Both arrays are on the heap; only the reference variables are on the stack. (A String[]'s cells are references to separate String objects.)
dynamicArr = null does not delete the array; it only breaks the link. The array is now unreachable, so the garbage collector reclaims it later.
When the method returns, its stack frame and references go automatically; unreferenced arrays are collected in time. Java has no free/delete.
Memory and Errors
Index Out of Bounds
- Accessing an index outside the array's bounds (0 … length − 1) makes Java throw, at run time, an
ArrayIndexOutOfBoundsException(a subclass ofIndexOutOfBoundsException). - If not caught, the program crashes at that line; it does not silently corrupt other memory as C does.
int[] arr = {10, 20, 30, 40, 50}; int index = 5; // check 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]);
Output
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 message gives the bad index (5), the array length (5) and the line number: the first place to look.
Memory and Errors
Classic Bug: Looping with <=
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 condition3 <= 3is still true, and the loop tries to writearr[3].- Correct condition:
i < arr.length; with a constant (i < 3) in place oflength, the code would break when the size changes.
Memory and Errors · Step-by-step code trace
Looping with <=: Which Pass Fails?
A 4-cell array; valid indices are 0 … 3, sq.length = 4.
i = 0: condition 0 <= 4 true.
sq[0] = 0.
i = 1: 1 <= 4 true.
sq[1] = 1.
i = 2: true.
sq[2] = 4.
i = 3: true.
sq[3] = 9: the last valid cell is filled.
i = 4: 4 <= 4 is also true! With < the loop would have ended here.
sq[4] does not exist: the JVM throws ArrayIndexOutOfBoundsException, and the program stops at this line; “done” is never printed.
int[] sq = new int[4]; for (int i = 0; i <= sq.length; i++) { sq[i] = i * i; } System.out.println("done");
Statistics Examples
Reading an Array from the User
import java.util.Scanner; public class Average { public static void main(String[] args) { // read the array size from the user Scanner scanner = new Scanner(System.in); System.out.print("enter size: "); int size = scanner.nextInt(); // read the elements into a new array double[] arr = new double[size]; for (int i = 0; i < size; i++) { System.out.print("element " + (i + 1) + ": "); arr[i] = scanner.nextDouble(); } // ... computations on the array } }
Sample run (input in bold)
enter size: 4 element 1: 7 element 2: 3 element 3: 9 element 4: 5
- The array size comes from the user:
new double[size]. The size is fixed at run time and never changes. - The prompt prints
i + 1(users count from 1); the value is stored witharr[i](from 0). - The mean, median and mode programs all start with this input part.
Statistics Examples · Step-by-step code trace
Average: Trace the Code Step by Step
The user enters 4 as the size.
nextInt() reads an integer from the keyboard: size = 4. Only now, at run time, is the array size known.
new double[size]: a 4-cell array, all 0.0.
i = 0: the prompt element 1: is printed, the user enters 7 → arr[0] = 7.0.
i = 1: the prompt element 2: is printed, the user enters 3 → arr[1] = 3.0.
i = 2: the prompt element 3: is printed, the user enters 9 → arr[2] = 9.0.
i = 3: the prompt element 4: is printed, the user enters 5 → arr[3] = 5.0.
sum += arr[0] → sum = 7.0.
sum += arr[1] → sum = 10.0.
sum += arr[2] → sum = 19.0.
sum += arr[3] → sum = 24.0.
mean = 24.0 / 4 = 6.0. sum is a double, so the division is floating-point.
The second loop prints the elements side by side; the values appear as double values, like 7.0. Then println() ends the line.
The result is printed.
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("element " + (i + 1) + ": "); 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);
Statistics Examples
Median
// size and arr are read as in Average 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);
Sample run
input: 7 3 9 5 1 Elements (sorted): 1.0 3.0 5.0 7.0 9.0 Median: 5.0
median must be declared outside the branches; if it is declared only inside them, the compiler reports error: cannot find symbol … variable median. import java.util.Arrays; is required.
Statistics Examples
Median: Odd and Even Counts
The input is unsorted: the middle cell (9.0) is not the median.
Arrays.sort(arr) has run. Size 5 (odd): arr[5 / 2] = arr[2] → median 5.0. Integer division truncates 2.5 to 2.
Size 4 (even; input 7 3 9 5): mid1 = 4/2 − 1 = 1, mid2 = 4/2 = 2 → (5.0 + 7.0) / 2 = 6.0.
Arrays.sort changes the array in place; the input order is lost. To keep it, first take arr.clone().Statistics Examples
Mode
- First,
Arrays.sort(arr): equal values end up next to each other. - Then a single pass finds the longest "run": each element is compared with the one before it.
Printing the result, and output (input: 7, then 4 2 7 2 4 2 9)
// 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)
Statistics Examples · Step-by-step code trace
Mode: Counting Runs Step by Step
The array has already been sorted: equal values are now adjacent. The first element is the candidate for both current and mode (1 time).
arr[1] = 2 == arr[0] = 2 → the run continues, currentCount = 2. 2 > previous best → mode is 2 (2 times).
arr[2] = 2 == arr[1] = 2 → the run continues, currentCount = 3. 3 > previous best → mode is 2 (3 times).
arr[3] = 4 ≠ arr[2] = 2 → a new run starts: currentValue = 4, count 1.
arr[4] = 4 == arr[3] = 4 → the run continues, currentCount = 2.
arr[5] = 7 ≠ arr[4] = 4 → a new run starts: currentValue = 7, count 1.
arr[6] = 9 ≠ arr[5] = 7 → a new run starts: currentValue = 9, count 1.
i = 7: the loop ends. Mode = 2, occurring 3 times. With runs of equal length, the > comparison would keep the first one found.
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; } }
Array Algorithms · Step-by-step code trace
Linear Search
The simplest way to find an element in an array: look at every element in order, from first to last.
main, linearSearch(arr, 30): main calls it. The method receives the array's reference and 30.
item = 10: 10 == 30 is false → go to the next element.
item = 20: 20 == 30 is false → go to the next element.
item = 30: 30 == 30 → true. The loop stops early and returns true.
The method's frame is popped off the stack: result = true. 3 comparisons were enough; 40 and 50 were never examined. For a target of 35 it would return false after 5 comparisons.
static boolean linearSearch(int[] arr, int target) { for (int item : arr) { if (item == target) { return true; } } return false; } // in main: int[] arr = {10, 20, 30, 40, 50}; boolean result = linearSearch(arr, 30);
Array Algorithms
Cost of Linear Search
- In the worst case the whole array is scanned: n comparisons for n elements.
- Time complexity is O(n) (n: array size): work grows in direct proportion to input size.
- Best case: the target is first: 1 comparison.
- Worst case: the target is last or absent.
- Unsorted, nothing beats this: "absent" needs a look at every element.
int[] arr = {10, 20, 30, 40, 50}; // search an array for a given element int key = 30; boolean found = false; for (int item : arr) { if (item == key) { found = true; break; } } // this is O(n)
break exits as soon as the target is found: only 3 elements are checked and found = true.
Array Algorithms
Binary Search
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; // range is empty } // in main: int[] arr = {3, 9, 14, 27, 42, 48, 55, 61, 70}; System.out.println(binarySearch(arr, 48)); System.out.println(binarySearch(arr, 50));
Output
5 -1
- Works only on a sorted array: look at the middle element; if the target is smaller, search the left half, otherwise the right half.
- For 48 the middle indices are 4 (42), 6 (55), 5 (48): 3 comparisons. For 50 the range becomes empty once 6 > 5, and the method returns
-1. - Each step halves the search range: O(log n). For n = 1000 at most 10 comparisons, for n = 1,000,000 at most 20.
Arrays.binarySearchuses the same method; on an unsorted array its result is meaningless.
Array Algorithms · Step-by-step code trace
Matching: Common Elements
Call: match(new int[]{3, 7, 1}, new int[]{5, 1, 3, 8})
Outer loop e1 = 3: the inner loop compares it with all 4 elements of arr2. A match is found → printed.
Outer loop e1 = 7: the inner loop compares it with all 4 elements of arr2. No match.
Outer loop e1 = 1: the inner loop compares it with all 4 elements of arr2. A match is found → printed.
In total 3 × 4 = 12 comparisons. For arrays of n elements, that is n × n = n² comparisons.
static void match(int[] arr1, int[] arr2) { for (int e1 : arr1) { for (int e2 : arr2) { if (e1 == e2) { System.out.println("Match: " + e1); } } } }
Array Algorithms
Complexity: O(1), O(n), O(n²)
Why is access O(1)?
Cells are contiguous and of equal size (int = 4 bytes), so the address of element i takes one multiply and one add to compute: address = start + i × 4. arr[2] and arr[1000000] take the same time to read.
| Operation | Complexity | for n = 1000 |
|---|---|---|
Access arr[i] | O(1) constant | 1 |
| Linear search | O(n) linear | ≤ 1000 |
| Reversal | O(n) | 500 swaps |
| Matching (nested) | O(n²) quadratic | 1,000,000 |
| Selection sort | O(n²) | ≈ 500,000 |
Array Algorithms
Selection Sort
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; } }
- Selection sort: at each step the smallest element is found and placed at the front of the unsorted part.
- The outer loop runs n − 1 times, the inner loop scans the rest → O(n²) comparisons, at most n − 1 swaps.
- Swap inside the array, using a temporary variable.
swap(int x, int y) as a swap method does not work: the method receives only copies of the elements. A working version takes the array itself: swap(int[] a, int i, int j).Array Algorithms · Step-by-step code trace
{64, 25, 12, 22, 11}: Step by Step
Start: no element is in place. Each pass finds the smallest element of the remaining part and puts it at the front of that part.
Pass i = 0: the inner loop searches j = 1…4 for the smallest value → 11 (index 4).
arr[0] and arr[4] swapped. The first cell is now in final position.
Pass i = 1: the inner loop searches j = 2…4 for the smallest value → 12 (index 2).
arr[1] and arr[2] swapped. The first 2 cells are now in final position.
Pass i = 2: the inner loop searches j = 3…4 for the smallest value → 22 (index 3).
arr[2] and arr[3] swapped. The first 3 cells are now in final position.
Pass i = 3: the inner loop searches j = 4…4 for the smallest value → 25 (index 3).
The minimum is already in place; it is swapped with itself (no change). After 4 passes the last element is in place too: the array is sorted.
int[] arr = {64, 25, 12, 22, 11}; selectionSort(arr); // selectionSort prints after each pass: // System.out.println("i=" + i + ": " // + Arrays.toString(arr));
Array Algorithms
Bubble Sort
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]) { // out of 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 swaps: sorted } }
Output: {64, 25, 12, 22, 11, 36, 48}
[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]
- Bubble sort: two neighbors out of order are swapped; on each pass the largest element “bubbles up” to the end.
- Each line is the result of one pass. After each pass the largest element is at the end, so the inner loop only runs up to
n - 1 - pass. swappedflag: on pass 5 there are no swaps, so the array is sorted andbreakstops early. A sorted array needs just one pass: O(n).- In the worst case it is still O(n²) comparisons; unlike selection sort, the number of swaps can also be O(n²).
Array Algorithms
Reversing an Array
static void reverse(int[] arr) { int left = 0; int right = arr.length - 1; while (left < right) { // swap the end elements int tmp = arr[left]; arr[left] = arr[right]; arr[right] = tmp; // move both indices inward left++; right--; } }
- The two-pointer technique: one index comes from the front, one from the back; each pass swaps the two end elements.
- About n/2 swaps → O(n); no extra array is needed (in place).
- The method is
void, but since it receives a copy of the array's reference, the caller's array changes.
Output
[1, 2, 3, 4, 5] → [5, 4, 3, 2, 1] [1, 2, 3, 4] → [4, 3, 2, 1]
Array Algorithms · Step-by-step code trace
reverse: Step by Step
Two pointers: left = 0 starts from the left, right = length − 1 = 4 from the right.
0 < 4 → tmp is used to swap arr[0] and arr[4] (tmp = 1).
1 < 3 → tmp is used to swap arr[1] and arr[3] (tmp = 2).
left = right = 2: 2 < 2 is false → the loop ends; the middle element stays put. The method returns nothing, yet the caller's array has changed: [5, 4, 3, 2, 1].
static void reverse(int[] arr) { int left = 0; int right = arr.length - 1; while (left < right) { int tmp = arr[left]; arr[left] = arr[right]; arr[right] = tmp; left++; right--; } }
Multidimensional Arrays
Two-Dimensional Arrays (Matrices)
- Multidimensional arrays store data along more than one dimension; Java supports two-dimensional (matrix) and higher-dimensional arrays.
- A two-dimensional array is a table-like structure of rows and columns: a chessboard, an image, a grade sheet.
- Access:
matrix[row][col]; the first index is the row, the second the column.
int[][] matrix = new int[3][3]; // a 3x3 matrix matrix[1][2] = 6; // row 2, column 3
Multidimensional Arrays
Initialization and Arrays of Arrays
- Two-dimensional arrays can also take an initializer list; no size is needed.
- In Java a 2D array is really an array of arrays:
matrix[i]is row i itself, that is, anint[]. matrix.length= row count,matrix[0].length= the first row's column count.
int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
System.out.println(matrix.length + " "
+ matrix[0].length + " " + matrix[1][2]);Output
3 3 6
Multidimensional Arrays
Ragged Arrays
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(); }
Output
1 2 3 1 2 3 4 5
- Rows are separate arrays, so they can differ in length.
new int[3][]creates only the row references (allnull); the rows are allocated later.- That is why using
matrix[i].lengthin the inner loop is safer than a fixed column count. for-each: each outer-loop element is anint[]row.
Multidimensional Arrays · Step-by-step code trace
Pascal's Triangle: A Ragged Array, Row by Row
new int[4][] reserves only 4 row references; all are null.
i = 0: a 1-cell row is created (filled with 0) and p[0] points to it.
The row's first and last cell are the same cell: 1.
i = 1: a 2-cell row.
Ends are 1; no inner cells (j < 1 is false at once).
i = 2: a 3-cell row.
Ends are 1.
p[2][1] = p[1][0] + p[1][1] = 1 + 1 = 2.
i = 3: a 4-cell row.
Ends are 1.
p[3][1] = p[2][0] + p[2][1] = 1 + 2 = 3.
p[3][2] = p[2][1] + p[2][2] = 2 + 1 = 3.
Row lengths are 1, 2, 3, 4: a ragged array. The last row is [1, 3, 3, 1].
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]));
Multidimensional Arrays
Example: MultiDimExample
public class MultiDimExample { public static void main(String[] args) { // a 3x3 two-dimensional array (matrix) int[][] matrix = new int[3][3]; // fill the matrix with initial values for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { matrix[row][col] = row * 3 + col + 1; } } // print the matrix 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(); // next line } } }
Output
Matrix contents: 1 2 3 4 5 6 7 8 9
row * 3 + col + 1 numbers the cells from 1 to 9.Multidimensional Arrays · Step-by-step code trace
Filling and Printing a Matrix: Step by Step
new int[3][3]: 3 rows × 3 columns, all cells 0.
matrix[0][0] = 0 * 3 + 0 + 1 = 1
matrix[0][1] = 0 * 3 + 1 + 1 = 2
matrix[0][2] = 0 * 3 + 2 + 1 = 3
matrix[1][0] = 1 * 3 + 0 + 1 = 4. The inner loop is done; the outer loop moves to the next row.
matrix[1][1] = 1 * 3 + 1 + 1 = 5
matrix[1][2] = 1 * 3 + 2 + 1 = 6
matrix[2][0] = 2 * 3 + 0 + 1 = 7. The inner loop is done; the outer loop moves to the next row.
matrix[2][1] = 2 * 3 + 1 + 1 = 8
matrix[2][2] = 2 * 3 + 2 + 1 = 9
The print loop visits cells in the same order; at the end of each row println() moves to a new line.
int[][] matrix = new int[3][3]; for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { matrix[row][col] = row * 3 + col + 1; } } 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(); }
Multidimensional Arrays
Three or More Dimensions
- Java also allows three- and higher-dimensional arrays: each extra dimension is one more pair of brackets.
- More dimensions allow richer data: a building
[floor][row][col], a color image[y][x][channel], a table of measurements over time. - The element count is the product:
new int[3][3][3]→ 3 × 3 × 3 = 27 cells. Memory grows fast as dimensions are added.
// a 3x3x3 three-dimensional array int[][][] arr3d = new int[3][3][3]; arr3d[1][2][0] = 16; // layer 1, row 2, column 0
Three-dimensional array: 3 layers, each a 3×3 matrix
Multidimensional Arrays
Example: ThreeDimExample
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(); }
Output
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: z runs along a row, y through a layer, x through the whole array. A blank line follows each layer.
Multidimensional Arrays
Matrix Transpose
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); }
Output
Original matrix: 1 2 3 4 5 6 Transposed matrix: 1 4 2 5 3 6
- The transpose turns a matrix's rows into columns and its columns into rows:
T[j][i] = M[i][j]. - The transpose of a 2×3 matrix is 3×2:
new int[cols][rows].
Multidimensional Arrays · Step-by-step code trace
Transpose: Copying Cell by Cell
rows = 2, cols = 3; a new 3×2 array is created for the transpose (cells 0).
transposed[0][0] = matrix[0][0] = 1 · the matrix's row becomes the transpose's column.
transposed[1][0] = matrix[0][1] = 2
transposed[2][0] = matrix[0][2] = 3
transposed[0][1] = matrix[1][0] = 4 · the matrix's row becomes the transpose's column.
transposed[1][1] = matrix[1][1] = 5
transposed[2][1] = matrix[1][2] = 6
for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { transposed[j][i] = matrix[i][j]; } }
Multidimensional Arrays
Helper Method: printMatrix
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(); } }
- Printing has been moved into a helper method;
maincalls it twice: first for the matrix, then for the transpose. - The parameter
int[][] matrix: works with a 2D array of any size, since the row countmatrix.lengthand the column countmatrix[i].lengthare read from the array. - The method receives not a copy of the array but its reference; the call is cheap even for a big matrix.
- With a fixed
3, one of the 2×3 and 3×2 matrices would print wrong or throw anArrayIndexOutOfBoundsException.
Practice: Tic Tac Toe
Tic Tac Toe
- The game uses a 3×3 board:
char[][] board = new char[3][3]; - Two players (X and O) take turns; each move is a single assignment:
board[row][col] = player. - Whoever places 3 of their marks in one row, column or diagonal wins.
- If no empty cell is left, the game is a draw.
The board on the right shows the array assignment run by each click.
Practice: Tic Tac Toe
TicTacToe: main
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'; // X moves first 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 }
- The work is split into methods: fill, print, read a move, check.
- Methods receive a copy of the board's reference: the change made by
makeMoveis visible inmain. - The methods must be
static; otherwise:
error: non-static method initBoard(char[][]) cannot be referenced from a static context
Practice: Tic Tac Toe
TicTacToe: Filling and Printing 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
------------- | | | | ------------- | | | | ------------- | | | | -------------
new char[3][3]cells start as'\u0000'; so that the board prints neatly and empty cells can be checked, they are first filled with' '(a space)."\n-------------": the line break and the separator in a singleprintln.
Practice: Tic Tac Toe
TicTacToe: Reading 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 + ", 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; }
- 1 turns it into index 0–2.board[row][col]: || stops at the first true condition, so no out-of-bounds access happens.Practice: Tic Tac Toe
TicTacToe: Is There a Winner?
public static boolean isRunning(char[][] board, char player) { // check the winning lines 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 check
- The 8 winning lines are checked one by one: each needs all 3 cells to hold
player(&&), and one line is enough (||). - Only the player who just moved is checked: only they can have completed a new line.
- If there is a winner, the method returns
false: "the game is not running".
Practice: Tic Tac Toe
TicTacToe: Is It a Draw?
// isRunning, continued // 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;
- First, a draw is assumed (
draw = true); a single empty cell disproves it. - The inner
breakleaves only the inner loop; the outerif (!draw) break;ends the outer loop too. - With no winner and an empty cell left, it returns
true: the game goes on. - Win is checked before draw: the last move may fill the board and win at the same time.
Practice: Tic Tac Toe · Step-by-step code trace
Draw: Two breaks, Two Loops
Board: X O X · O X ␣ · O X O (␣: space character)
A draw is assumed first. The board has one empty cell: (1, 2).
(0, 0) = 'X': not empty, continue.
(0, 1) = 'O': not empty.
(0, 2) = 'X': row 0 is full; the inner loop ends on its own.
!draw is false: the outer loop goes on.
i = 1: (1, 0) = 'O'.
(1, 1) = 'X'.
(1, 2) = ' ': empty cell found.
The assumption fails: draw = false.
The inner break: it leaves only the inner loop; the outer loop is still running.
!draw true.
Outer break: row 2 is never checked.
There is an empty cell: continue is printed.
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");
Practice: Tic Tac Toe
A Sample Game
X 1 1 → board[0][0] = 'X'. No winner, empty cells left → true; O's turn.
O 1 2 → board[0][1] = 'O'. No winner, empty cells left → true; X's turn.
X 2 2 → board[1][1] = 'X'. No winner, empty cells left → true; O's turn.
O 2 2: board[1][1] is taken (!= ' ') → do-while condition is true, so the same prompt repeats.
O 1 3 → board[0][2] = 'O'. No winner, empty cells left → true; X's turn.
X 3 3 → board[2][2] = 'X'. Main diagonal X → winning message; isRunning returns false and the loop ends.
Input (row column)
1 1 1 2 2 2 2 2 1 3 3 3
Final output of the program
Congratulations, player X wins! ------------- | X | O | O | ------------- | | X | | ------------- | | | X | -------------
Summary
Summary
| Topic | Key point |
|---|---|
| Array | A fixed number of elements of one type; indices 0 … length − 1 |
| Creation | new int[n] (default values) · {1, 2, 3} (declaration only) · new int[]{…} |
| length | A field, no parentheses: arr.length; in 2D, m.length rows, m[i].length columns |
| Reference | The variable holds an address; b = a same array, clone()/Arrays.copyOf new array; == compares addresses |
| Memory | All arrays live on the heap, references on the stack; the garbage collector frees unreachable arrays |
| Errors | Out-of-bounds index → ArrayIndexOutOfBoundsException; in loops use i < length |
| Algorithms | Access O(1) · binary search O(log n) · linear search, reversal O(n) · matching, selection and bubble sort O(n²) |
| Multiple dimensions | Arrays of arrays; nested loops; rows may differ in length |
Summary
Common Mistakes (1)
a = {1, 2, 3};error: illegal start of expression → a = new int[]{1, 2, 3};length() with parenthesesa.length()error: cannot find symbol … method length() → a.lengthnew int[]error: array dimension missingint[] a = {1, 2.5, 3};error: incompatible types: possible lossy conversion from double to interror: cannot find symbol … variable medianstatic missing on a methoderror: non-static method … cannot be referenced from a static contextSummary
Common Mistakes (2)
a[a.length] or i <= a.length: ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3int[] a = null; a[0]: NullPointerException: Cannot load from int array because "a" is nullSystem.out.println(a) → [I@7ef20235. For the contents use Arrays.toString(a).b = a; then changing b[0] changes a[0] too. To copy: a.clone().== for comparing contentsTwo arrays with equal elements give false. For the contents use Arrays.equals(a, b).arr[0]: "element " + (i + 1).Summary
Worked Problems (1)
static int mystery(int[] d) { int s = 0; for (int i = 0; i < d.length; i += 2) { s += d[i]; } return s; } static void modify(int[] d, int x) { d[0] = 100; x = 100; } // main: int[] d = {4, 8, 15, 16, 23, 42}; int[] a = {1, 2, 3}; int x = 1; modify(a, x);
mystery(d): what does it return? What does the method compute?d[d.length / 2]= ?modify(a, x): what area[0]andx? Why do they differ?
Show answers
- 42: the sum of the even-index elements, 4 + 15 + 23.
- 6 / 2 = 3 →
d[3]= 16. - 100 1: the method gets a copy of the array's reference, so the cell changes;
xis a copy, and the original variable stays 1.
Summary
Worked Problems (2)
int[][] m = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int trace = 0; for (int i = 0; i < m.length; i++) { trace += m[i][i]; } // --- int[] b = new int[5]; for (int i = 1; i < b.length; i++) { b[i] = b[i - 1] + i; } System.out.println(Arrays.toString(b)); // --- int[] p = {3, 1, 2}; int[] q = p; q[2] = q[0] + q[1]; System.out.println(Arrays.toString(p));
- In the first snippet, what is
trace? Which cells are added? - What does the second snippet print?
- What does the third snippet print?
Show answers
- 15: the diagonal
m[0][0] + m[1][1] + m[2][2]= 1 + 5 + 9 (the trace of the matrix). - [0, 1, 3, 6, 10]: each cell adds its index to the previous one (0, 0+1, 1+2, 3+3, 6+4).
- [3, 1, 4]:
qandpare the same array; writingq[2] = 3 + 1changesptoo.
Summary
Exercises
int max(int[] arr): return the largest element.{12, 7, 30, 5, 18}→ ?int countEven(int[] arr): count the even elements (with for-each). Same array → ?int indexOf(int[] arr, int target): index of the target, or −1. For 5 and 99 → ?int[][] add(int[][] a, int[][] b): matrix sum.{{1, 2}, {3, 4}}+{{5, 6}, {7, 8}}→ ?int[] rowSums(int[][] m): each row's sum.{{1, 2, 3}, {4, 5, 6}}→ ?- Add
isBoardFullto Tic Tac Toe; use it for the draw check.
Answers / hints
- Start with
best = arr[0], scan fromi = 1→ 30. (Starting at 0 fails for all-negative arrays.) if (x % 2 == 0) count++;→ 3 (12, 30, 18).- A classic
for(you need the index) → 3 and −1. c[i][j] = a[i][j] + b[i][j]→ [[6, 8], [10, 12]].t[i] += m[i][j]→ [6, 15].- Two loops look for
' ': if found,return false; after the loops,return true.
Summary
References
- Oracle, The Java Tutorials: Arrays; The for Statement (enhanced for).
- Oracle, Java SE 21 API:
java.util.Arrays. - J. Gosling et al., The Java Language Specification, Java SE 21 Edition (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.
- C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed., Pearson (3.10 Arrays).
- A. Downey and C. Mayfield, Think Java, 2nd ed., O'Reilly (Chapter 7: Arrays and References).