Chapter 10: Arrays
Introduction
Learning Outcomes
Declare and initialize arrays.
Use indices and length.
Traverse and transform arrays with loops.
Work with rows and columns of two-dimensional arrays.
Basics
What Is an Array?
- Stores a fixed number of elements of one type in consecutive cells of a single object.
- Elements are accessed by a zero-based index:
nums[0]…nums[4]. - The length (
length) cannot change after creation. - An array variable holds not the elements but a reference (address) to the array object on the heap.
Variable → array object (reference arrow)
Basics
Arrays and Indices
- The first index is 0, the last is length − 1 (5 elements → 0…4).
- The address of
a[i]is computed directly (start + i × cell size), so access takes constant time (O(1)) without walking the array.
Basics
Strengths and Limits
| Strength | Limit |
|---|---|
| Fast access by index | Fixed size |
| Consistent element type | Inserting in the middle is costly |
| Easy to process with loops | Out-of-bounds access is a run-time error |
| Regular layout in memory | Holds a single element type |
Declaration
Creating Arrays
int[] nums = new int[5]; String[] names = {"Ada", "Can", "Ece"}; double[] readings; readings = new double[10];
- Cells of an array created with
newget the type's default value (right). - With an initializer
{…}the length comes from the number of values (names.length = 3).
Default initial values
Declaration · Step through the code
Code Trace: Creating an Array
Declaration: only the reference variable nums appears on the stack; there is no array yet.
new int[4] creates a 4-cell array on the heap, all 0. The variable gets the array's reference (arrow).
nums[0] = 7: follow the arrow and write 7 into cell 0.
nums[3] = 2: the last cell (index length − 1 = 3) is updated.
Initializer {…}: 3 values → an array of length 3 is built and names refers to it.
length is a field (no parentheses): 4 and 3 are printed.
int[] nums; nums = new int[4]; nums[0] = 7; nums[3] = 2; String[] names = {"Ada", "Can", "Ece"}; System.out.println(nums.length + " " + names.length);
Access · Step through the code
Reading and Writing Elements
A three-element array; indices 0, 1, 2.
Read: scores[0] gives the value in the first cell → first = 70.
Write: scores[1] on the left of an assignment is the cell itself; 85 is overwritten with 88.
scores.length - 1 = 3 − 1 = 2 → the last element is 90. The code stays correct if the size changes.
The two values are printed with a space between them.
int[] scores = {70, 85, 90}; int first = scores[0]; scores[1] = 88; int last = scores[scores.length - 1]; System.out.println(first + " " + last);
Access
Out-of-Bounds Errors
- Valid indices run from 0 to length − 1; negative indices and
lengthitself are invalid. - The compiler doesn't catch this; the program stops at run time with
ArrayIndexOutOfBoundsException.
i < arr.length; <= runs one pass too many.Access · Step through the code
Code Trace: One Pass Too Many (<=)
An array of length 3: valid indices 0, 1, 2.
0 <= 3 → true, enter the body.
a[0] = 4 is printed.
i++ → 1 <= 3 → true, enter the body.
a[1] = 8 is printed.
i++ → 2 <= 3 → true, enter the body.
a[2] = 6 is printed.
i++ → 3 <= 3 → true. Careful: 3 is an invalid index, yet the condition holds!
a[3]: no such cell → the program stops with an error. Fix: make the condition i < a.length.
int[] a = {4, 8, 6}; for (int i = 0; i <= a.length; i++) { System.out.println(a[i]); }
Loops · Step through the code
Traversal with a Classic for
The array is ready; the index i will start at 0.
int i = 0; 0 < 3 → true
scores[0] = 70; %d: %d format gives 0: 70.
i++ → 1 < 3 → true
scores[1] = 88; %d: %d format gives 1: 88.
i++ → 2 < 3 → true
scores[2] = 90; %d: %d format gives 2: 90.
i++ → 3 < 3 → false → the loop ends; since i = length, scores[i] is never accessed.
int[] scores = {70, 88, 90}; for (int i = 0; i < scores.length; i++) { System.out.printf("%d: %d%n", i, scores[i]); }
Use a classic for when you need the index (printing positions, looking at a neighbor, writing to a cell).
Loops · Step through the code
The Enhanced for (for-each)
The enhanced for hands out the elements in order; there is no index.
Pass 1: score gets a copy of scores[0] (70).
score = 75; the array cell stays 70: only the copy changed.
75 is printed.
Pass 2: score gets a copy of scores[1] (88).
score = 93; the array cell stays 88: only the copy changed.
93 is printed.
Pass 3: score gets a copy of scores[2] (90).
score = 95; the array cell stays 90: only the copy changed.
95 is printed.
No elements left → the loop ends; score goes out of scope.
scores[0] is still 70: in an enhanced for, assigning to the loop variable doesn't change the array.
int[] scores = {70, 88, 90}; for (int score : scores) { score = score + 5; System.out.println(score); } System.out.println(scores[0]);
Operations · Step through the code
Sum and Average
A four-element array.
The accumulator starts at sum = 0.
value = 4 → sum += value: 0 + 4 = 4.
value = 7 → sum += value: 4 + 7 = 11.
value = 2 → sum += value: 11 + 2 = 13.
value = 6 → sum += value: 13 + 6 = 19.
The loop is done. avg starts at 0 (a safe value for an empty array).
4 > 0 → true: the array isn't empty, so dividing is safe.
(double) 19 / 4 = 4.75. Without the cast, integer division would give 4.
The results are printed.
int[] nums = {4, 7, 2, 6}; int sum = 0; for (int value : nums) sum += value; double avg = 0; if (nums.length > 0) avg = (double) sum / nums.length; System.out.println(sum + " " + avg);
Operations · Step through the code
Minimum and Maximum
Array: 5, 3, 9, 1.
The first element is the candidate for both min and max (starting at 0 would fail for all-negative or all-positive arrays).
Pass 1: value = 5.
5 < 5 → false; min unchanged.
5 > 5 → false; max unchanged.
Pass 2: value = 3.
3 < 5 → true: min = 3.
3 > 5 → false; max unchanged.
Pass 3: value = 9.
9 < 3 → false; min unchanged.
9 > 5 → true: max = 9.
Pass 4: value = 1.
1 < 3 → true: min = 1.
1 > 9 → false; max unchanged.
Every element checked (n = 4 passes) → 1 9.
int[] nums = {5, 3, 9, 1}; int min = nums[0], max = nums[0]; for (int value : nums) { if (value < min) min = value; if (value > max) max = value; } System.out.println(min + " " + max);
nums[0] fails on an empty array; real code should handle nums.length == 0 first.
Operations · Step through the code
Reversing an Array (two pointers)
The array to reverse.
Two pointers: left = 0 and right = length − 1 = 4.
0 < 4 → true, so the ends get swapped.
tmp = arr[0] = 1: the left value is saved so it isn't lost.
arr[0] = arr[4] → 5 goes into the left cell.
arr[4] = tmp → 1 goes into the right cell. Swap done.
The pointers move inward: left = 1, right = 3.
1 < 3 → true, so the ends get swapped.
tmp = arr[1] = 2: the left value is saved so it isn't lost.
arr[1] = arr[3] → 4 goes into the left cell.
arr[3] = tmp → 2 goes into the right cell. Swap done.
The pointers move inward: left = 2, right = 2.
2 < 2 → false: the pointers met in the middle → the array is reversed.
int[] arr = {1, 2, 3, 4, 5}; int left = 0, right = arr.length - 1; while (left < right) { int tmp = arr[left]; arr[left] = arr[right]; arr[right] = tmp; left++; right--; }
n/2 swaps; no extra array needed (in place, O(1) extra space).
Operations · Step through the code
Counting Values Above the Average
Five students' grades. First the average, then those above it: two passes are needed.
Pass 1: accumulate the sum.
x = 60 → sum = 60.
x = 75 → sum = 135.
x = 90 → sum = 225.
x = 45 → sum = 270.
x = 80 → sum = 350.
(double) 350 / 5 = 70.0.
Counter for pass 2: above = 0.
60 > 70.0 → false.
75 > 70.0 → true: above = 1.
90 > 70.0 → true: above = 2.
45 > 70.0 → false.
80 > 70.0 → true: above = 3.
The average is 70.0; 3 grades are above it.
int[] grades = {60, 75, 90, 45, 80}; int sum = 0; for (int x : grades) sum += x; double avg = (double) sum / grades.length; int above = 0; for (int x : grades) if (x > avg) above++; System.out.println(avg + " " + above);
Operations · Step through the code
The Second-Largest Element of an Array
Both candidates start at the smallest int (Integer.MIN_VALUE); each element is examined once.
7 > MIN → new largest: the old largest (MIN) drops to second, largest = 7.
12 > 7 → new largest: the old largest (7) drops to second, largest = 12.
No change: 5 is not greater than second (7).
No change: 12 == largest (a repeat) doesn't count.
9 is smaller than the largest but greater than second, and 9 != 12 → second = 9.
One pass gives 9 (12 appears twice, but the second largest is 9). If second is still Integer.MIN_VALUE, there is no second distinct value (empty, single-element or all-equal array).
int[] a = {7, 12, 5, 12, 9}; int largest = Integer.MIN_VALUE; int second = Integer.MIN_VALUE; for (int x : a) { if (x > largest) { second = largest; largest = x; } else if (x > second && x != largest) { second = x; } } System.out.println(second);
Operations · Step through the code
Counting Frequencies: A Die Histogram
The rolls are fixed here (really rnd.nextInt(6) + 1). A 7-cell counter: index = die value (0 unused). This is the value as index trick.
die = 3 → count[3]++ → 1. No if-else chain needed!
die = 6 → count[6]++ → 1. No if-else chain needed!
die = 3 → count[3]++ → 2. No if-else chain needed!
die = 1 → count[1]++ → 1. No if-else chain needed!
die = 6 → count[6]++ → 2. No if-else chain needed!
die = 3 → count[3]++ → 3. No if-else chain needed!
y = 1: count[1] = 1 star.
y = 2: count[2] = 0 stars (none).
y = 3: count[3] = 3 stars.
y = 4: count[4] = 0 stars (none).
y = 5: count[5] = 0 stars (none).
y = 6: count[6] = 2 stars.
int[] rolls = {3, 6, 3, 1, 6, 3}; int[] count = new int[7]; for (int die : rolls) count[die]++; for (int y = 1; y <= 6; y++) { System.out.print(y + ": "); for (int k = 0; k < count[y]; k++) System.out.print("*"); System.out.println(); }
Operations · Step through the code
Sieve of Eratosthenes (boolean array)
All cells false: initially 2…20 are all prime candidates.
2 × 2 = 4 <= 20 → true.
2 is not crossed out → prime. Its multiples are marked starting from 2·2: k = 4, 6, 8, 10, 12, 14, 16, 18, 20.
3 × 3 = 9 <= 20 → true.
3 is not crossed out → prime. Its multiples are marked starting from 3·3: k = 9, 12, 15, 18.
4 × 4 = 16 <= 20 → true.
composite[4] = true → 4 is already crossed out; no need to visit its multiples.
5 × 5 = 25 <= 20 → false: no need to look for divisors above √20.
The numbers not crossed out are printed: 8 primes.
int n = 20; boolean[] composite = new boolean[n + 1]; for (int i = 2; i * i <= n; i++) if (!composite[i]) for (int k = i * i; k <= n; k += i) composite[k] = true; for (int i = 2; i <= n; i++) if (!composite[i]) System.out.print(i + " ");
Operations
Copying Arrays
b = acopies the reference, not the elements: two arrows point to the same object.- For an independent copy use
a.clone(),Arrays.copyOf(a, a.length)orSystem.arraycopy. - For arrays of objects these copy the element references; the objects themselves are not duplicated (shallow copy).
Operations · Step through the code
Code Trace: Copying a Reference vs. Copying Elements
One array on the heap; a refers to it.
b = a: no new array is created; b gets the same reference → two arrows on one object.
b[0] = 99: the object b refers to changed, and it is a's object too!
a[0] is now 99. A copied reference is not an independent array.
a.clone() creates a new array on the heap and copies the elements one by one.
c[1] = 50 changes only the copy.
a[1] = 2 (unchanged), c[1] = 50.
int[] a = {1, 2, 3}; int[] b = a; b[0] = 99; System.out.println(a[0]); int[] c = a.clone(); c[1] = 50; System.out.println(a[1] + " " + c[1]);
Operations
Arrays Utilities
import java.util.Arrays; int[] a = {5, 2, 9}, r = {10, 20, 30, 40, 50}, p = {1, 2, 3}, q = {1, 2, 3}, f = new int[4]; int[][] m = {{1, 2}, {3, 4}};
| Call | Result |
|---|---|
Arrays.toString(a) | [5, 2, 9] |
Arrays.deepToString(m) | [[1, 2], [3, 4]] |
Arrays.toString(m) | [[I@… (address) |
Arrays.fill(f, 7) → f | [7, 7, 7, 7] |
p == q / p.equals(q) | false / false |
Arrays.equals(p, q) | true |
| Copy (Arrays.) | Result |
|---|---|
copyOf(a, 5) | [5, 2, 9, 0, 0] |
copyOf(a, 2) | [5, 2] |
copyOfRange(r, 1, 4) | [20, 30, 40] |
==andequalscompare references; for contents useArrays.equals(deepEqualsfor 2D).copyOfpads with zeros if the length is larger and truncates if smaller; incopyOfRangethe end index is exclusive.
Search
Linear Search: search(d, 6)
static int search(int[] arr, int target) { for (int i = 0; i < arr.length; i++) if (arr[i] == target) return i; return -1; } // in main: int[] d = {8, 3, 6, 2}; System.out.println(search(d, 6));
| i | arr[i] | == 6 ? |
|---|---|---|
| 0 | 8 | false |
| 1 | 3 | false |
| 2 | 6 | true → return 2 |
- Output: 2. The loop ends early at the first match.
- The parameter
arrrefers to the same array asd(the reference is passed); no copy is made. - If the target is absent, −1 comes back after n comparisons → O(n).
Search
Sorting and Binary Search
Arrays.sort(a)sorts the array in ascending order in place (the original order is lost).Arrays.binarySearch(a, x)works only on a sorted array; it returns the index if found, otherwise a negative value,-(insertion point) - 1.- It halves the range at each step, so it makes far fewer comparisons than linear search.
- Both need
import java.util.Arrays;.
Search
The Median
- Median: the value in the middle of the sorted array; with an even count, the average of the middle two.
- Unaffected by outliers: for {1, 2, 3, 4, 100} the average is 22.0, the median 3.
Arrays.sortchanges the array in place, so a copy is sorted.- The
(double)cast comes before the addition: two large ints can't overflow and the division keeps the fraction.
int[] a = {7, 3, 9, 1, 5}; int[] s = Arrays.copyOf(a, a.length); Arrays.sort(s); // a is untouched int n = s.length; double m = (n % 2 == 1) ? s[n / 2] : (s[n/2 - 1] + (double) s[n/2]) / 2; System.out.println(m); // 5.0
Sorting
Bubble Sort
int[] a = {5, 1, 4, 2}; int n = a.length; for (int pass = 0; pass < n - 1; pass++) { for (int j = 0; j < n - 1 - pass; j++) { if (a[j] > a[j + 1]) { int tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp; } } }
| pass | array after pass | comp. | swap |
|---|---|---|---|
| 1 | [1, 4, 2, 5] | 3 | 3 |
| 2 | [1, 2, 4, 5] | 2 | 1 |
| 3 | [1, 2, 4, 5] | 1 | 0 |
- Each pass moves the largest remaining element to the end; the inner loop gets one shorter each pass.
- 3 + 2 + 1 = 6 comparisons in all → O(n²).
- No swaps in pass 3: the array was already sorted after pass 2.
Sorting
Insertion Sort
int[] a = {4, 3, 5, 1}; for (int i = 1; i < a.length; i++) { int key = a[i]; int j = i - 1; while (j >= 0 && a[j] > key) { a[j + 1] = a[j]; j--; } a[j + 1] = key; }
| i | key | shifted right | array after pass |
|---|---|---|---|
| 1 | 3 | 4 | [3, 4, 5, 1] |
| 2 | 5 | — | [3, 4, 5, 1] |
| 3 | 1 | 5, 4, 3 | [1, 3, 4, 5] |
- The left part is always sorted; elements larger than the key shift one place right, and the key drops into the gap.
- Very fast on nearly sorted arrays; O(n²) in the worst case (reverse order).
Search
Binary Search: target = 23
int[] a = {2, 5, 8, 12, 16, 23, 38, 56}; int target = 23, lo = 0, hi = a.length - 1; int result = -1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (a[mid] == target) { result = mid; break; } if (a[mid] < target) lo = mid + 1; else hi = mid - 1; } System.out.println(result);
| pass | lo | hi | mid | a[mid] | decision |
|---|---|---|---|---|---|
| 1 | 0 | 7 | 3 | 12 | 12 < 23 → lo = 4 |
| 2 | 4 | 7 | 5 | 23 | found: result = 5 |
- Output: 5. The array must be sorted.
- Found in 2 passes; linear search would need 6 comparisons → O(log n).
Search
Unsuccessful Search: Arrays.binarySearch(a, 5) → -3
static int search(int[] a, int x) { int lo = 0, hi = a.length - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (a[mid] == x) return mid; if (a[mid] < x) lo = mid + 1; else hi = mid - 1; } return -(lo + 1); } System.out.println(search(new int[]{2, 4, 6, 8}, 5));
| pass | lo | hi | mid | a[mid] | decision |
|---|---|---|---|---|---|
| 1 | 0 | 3 | 1 | 4 | 4 < 5 → lo = 2 |
| 2 | 2 | 3 | 2 | 6 | 6 > 5 → hi = 1 |
| — | 2 | 1 | lo > hi: the loop ends |
- The result
-(lo + 1)= -3; a negative value means “not found”. - Insertion point = -(-3) - 1 = 2: 5 would go at position 2.
Arrays.binarySearchreturns the same value.
Analysis
Basic Complexities
| Operation | Time |
|---|---|
| Index access | O(1) |
| Linear search | O(n) |
| Traverse to the end | O(n) |
| Insert / delete in the middle | O(n) |
| Two nested full traversals | O(n²) |
Matrices
Two-Dimensional Arrays
int[][] matrix = { {1, 2, 3}, {4, 5, 6} }; int value = matrix[1][2]; // 6
- The first index is the row, the second the column.
- In Java a multidimensional array is an array of arrays: each cell of the outer array points to a row array, and rows may differ in length (a jagged array).
matrix.length= number of rows,matrix[0].length= number of columns.
Matrices · Step through the code
A Jagged Array: new int[3][]
new int[3][] creates only the outer array (3 cells). The rows don't exist yet: all three cells are null.
m[0] = new int[1]: the first cell points to a one-element row. m[1] and m[2] are still null.
m[1] = new int[2]: the second row has 2 elements.
m[2] = new int[3]: the rows differ in length, which makes a jagged array. Each row is a separate object.
i = 0: m[0].length = 1 is printed.
i = 1: m[1].length = 2 is printed.
i = 2: m[2].length = 3. Output: 1 2 3. Reading m[i].length while a row is null would throw NullPointerException.
int[][] m = new int[3][]; m[0] = new int[1]; m[1] = new int[2]; m[2] = new int[3]; for (int i = 0; i < m.length; i++) System.out.print(m[i].length + " ");
Matrices · Step through the code
The Shallow-Copy Trap in 2D Arrays
a is an outer array pointing to two row arrays.
a.clone() copies only the outer array: both outer arrays point to the same row objects (shallow copy).
b[0][0] = 99: b[0] and a[0] are the same row → a[0][0] is 99 too.
b[1] = new int[]{7, 8} only points b's cell at a new row; a[1] is unchanged.
a: shared row 0 changed (99); row 1 is still {3, 4}.
For a real copy, copy each row as well: b[i] = a[i].clone().
int[][] a = {{1, 2}, {3, 4}}; int[][] b = a.clone(); b[0][0] = 99; b[1] = new int[]{7, 8}; System.out.println(Arrays.deepToString(a)); System.out.println(Arrays.deepToString(b));
Matrices · Step through the code
Traversing a Matrix Row by Row
A matrix of 2 rows × 3 columns; matrix.length = 2.
Outer loop: 0 < 2 → true → process row 0.
Inner loop: 0 < 3 → true; prints matrix[0][0] = 1 (print stays on the line).
Inner loop: 1 < 3 → true; prints matrix[0][1] = 2 (print stays on the line).
Inner loop: 2 < 3 → true; prints matrix[0][2] = 3 (print stays on the line).
3 < 3 → false: the row is done; leave the inner loop.
println() moves to the next line; then i++.
Outer loop: 1 < 2 → true → process row 1.
Inner loop: 0 < 3 → true; prints matrix[1][0] = 4 (print stays on the line).
Inner loop: 1 < 3 → true; prints matrix[1][1] = 5 (print stays on the line).
Inner loop: 2 < 3 → true; prints matrix[1][2] = 6 (print stays on the line).
3 < 3 → false: the row is done; leave the inner loop.
println() moves to the next line; then i++.
Outer loop: 2 < 2 → false → done. 2 × 3 = 6 cells visited in all.
int[][] matrix = {{1, 2, 3}, {4, 5, 6}}; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); }
Matrices · Step through the code
Matrix Transpose
The source matrix is 2 × 3.
matrix.length = number of rows = 2.
matrix[0].length = length of the first row = 3.
The target t has the dimensions swapped: 3 × 2, all cells 0.
t[0][0] = matrix[0][0] = 1: rows ↔ columns swap.
t[1][0] = matrix[0][1] = 2: rows ↔ columns swap.
t[2][0] = matrix[0][2] = 3: rows ↔ columns swap.
t[0][1] = matrix[1][0] = 4: rows ↔ columns swap.
t[1][1] = matrix[1][1] = 5: rows ↔ columns swap.
t[2][1] = matrix[1][2] = 6: rows ↔ columns swap.
The loops are done: the rows of matrix became the columns of t.
int[][] matrix = {{1, 2, 3}, {4, 5, 6}}; int rows = matrix.length; int cols = matrix[0].length; int[][] t = new int[cols][rows]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) t[j][i] = matrix[i][j];
Matrices · Step through the code
Matrix Multiplication (2×2)
C[i][j] = the sum of products of row i of A and column j of B. C starts as zeros.
C[0][0] += 1 × 5 → 0 + 5 = 5
C[0][0] += 2 × 7 → 5 + 14 = 19 (cell done)
C[0][1] += 1 × 6 → 0 + 6 = 6
C[0][1] += 2 × 8 → 6 + 16 = 22 (cell done)
C[1][0] += 3 × 5 → 0 + 15 = 15
C[1][0] += 4 × 7 → 15 + 28 = 43 (cell done)
C[1][1] += 3 × 6 → 0 + 18 = 18
C[1][1] += 4 × 8 → 18 + 32 = 50 (cell done)
Three nested loops: n³ multiplications for an n×n matrix → O(n³). The column count of A must equal the row count of B.
int[][] A = {{1, 2}, {3, 4}}; int[][] B = {{5, 6}, {7, 8}}; int[][] C = new int[2][2]; for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) for (int k = 0; k < 2; k++) C[i][j] += A[i][k] * B[k][j];
Design
Array or List?
- If the number of elements is known and fixed, an array is simple and fast.
- If the count will change, collections such as
ArrayListare more convenient. int[]stores the numbers directly;ArrayList<Integer>wraps each number in an object.- Choose based on usage, readability and measured performance.
Verification
Common Mistakes
i <= a.length reaches a[length] on the last pass → ArrayIndexOutOfBoundsException. Use i < a.length.
int min = a[0]; fails on an empty array; check a.length == 0 first.
int[] b = a; is not a new array; b[0] = 9 changes a too. Use a.clone() for a copy.
Not every row has length matrix[0].length; use matrix[i].length in the inner loop.
Summary
Chapter Summary
A fixed number of elements of one type; indices 0 … length − 1; the variable refers to the array.
a[i] reads and writes in constant time; an out-of-bounds index is a run-time error.
Classic for (when you need the index) and enhanced for (assigning to the loop variable leaves the array alone); sum, min-max, reversing, searching.
int[][] is an array of arrays: matrix.length rows, matrix[i].length columns.
Summary
Review Questions
- What is the last index of a five-element array?
- When is the enhanced for not enough?
- What is the difference between assigning an array and copying its elements?
- What precondition does binary search require?
- What do
matrix.lengthandmatrix[0].lengthgive?
Answers
- 4 (length − 1).
- When you need the index: printing positions, writing a new value to a cell, traversing backward or walking two arrays together.
- Assignment (
b = a) copies only the reference, so both variables refer to one object;clone/Arrays.copyOfcreate a new array. - The array must be sorted.
- The number of rows and the number of columns of the first row.
Summary
Exercises
- Write code that finds the count and sum of the even numbers in an
int[]. - Write code that rotates an array one position right (last element first) with no extra array: {1,2,3,4} → {4,1,2,3}.
- Merge two sorted arrays into a single sorted array (
{1,4,7}+{2,3,9}). - Add a
booleanflag to bubble sort that stops early when a pass makes no swaps. - Use the sieve of Eratosthenes to count the primes up to 100 (answer: 25).
- Compute the main-diagonal sum and the transpose of a 3×3 matrix; check whether it is symmetric.
Summary
References
- Deitel and Deitel, Java: How to Program, Early Objects, 11th ed., Pearson, 2018.
- Liang, Introduction to Java Programming and Data Structures, 13th ed., Pearson, 2024.
- Oracle, The Java Tutorials: Arrays.
- Oracle, Java SE 21 API: java.util.Arrays; Java Language Specification SE 21: Chapter 10, Arrays.
- Sedgewick and Wayne, Computer Science: An Interdisciplinary Approach, Addison-Wesley, 2016: 1.4 Arrays.
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed., MIT Press, 2022.