Chapter 10: Arrays

Computer Fundamentals and Introduction to Programming
DefinitionIndexLoopsSearchMatrices
Sercan KÜLCÜ · Giresun University

Introduction

Learning Outcomes

Creating

Declare and initialize arrays.

Access

Use indices and length.

Processing

Traverse and transform arrays with loops.

Matrices

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.
StackHeapnums0010203040length = 5 (fixed)same type: all int

Variable → array object (reference arrow)

Basics

Arrays and Indices

010120230340450aa.length = 5first: a[0]last: a[a.length − 1] = a[4]a[2] → 30
  • 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

StrengthLimit
Fast access by indexFixed size
Consistent element typeInserting in the middle is costly
Easy to process with loopsOut-of-bounds access is a run-time error
Regular layout in memoryHolds a single element type
Index access: a direct jump100201302403504address = start + 3 × cell sizea[3] → 40: one step, O(1)Insertion: 15 → index 1102030401015203040the 3 on the rightshift by oneIf full: new, larger array + copy (size is fixed)

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 new get the type's default value (right).
  • With an initializer {…} the length comes from the number of values (names.length = 3).
int[] a = new int[3];000double[] d = new double[3];0.00.00.0boolean[] b = new boolean[3];falsefalsefalseString[] s = new String[3];nullnullnull

Default initial values

Declaration · Step through the code

Code Trace: Creating an Array

Stack (variables)Heap (objects)nums?

Declaration: only the reference variable nums appears on the stack; there is no array yet.

Stack (variables)Heap (objects)00102030length = 4nums

new int[4] creates a 4-cell array on the heap, all 0. The variable gets the array's reference (arrow).

Stack (variables)Heap (objects)07102030length = 4nums

nums[0] = 7: follow the arrow and write 7 into cell 0.

Stack (variables)Heap (objects)07102032length = 4nums

nums[3] = 2: the last cell (index length − 1 = 3) is updated.

Stack (variables)Heap (objects)07102032length = 40Ada1Can2Ecelength = 3numsnames

Initializer {…}: 3 values → an array of length 3 is built and names refers to it.

Stack (variables)Heap (objects)07102032length = 40Ada1Can2Ecelength = 3numsnames

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

Stack (variables)Heap (objects)070185290length = 3scores

A three-element array; indices 0, 1, 2.

Stack (variables)Heap (objects)070185290length = 3scoresfirst70

Read: scores[0] gives the value in the first cell → first = 70.

Stack (variables)Heap (objects)070188290length = 3scoresfirst70

Write: scores[1] on the left of an assignment is the cell itself; 85 is overwritten with 88.

Stack (variables)Heap (objects)070188290length = 3scoresfirst70last90

scores.length - 1 = 3 − 1 = 2 → the last element is 90. The code stays correct if the size changes.

Stack (variables)Heap (objects)070188290length = 3scoresfirst70last90

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

0418263143-1✗5✗valid: 0 … length − 1 = 4a[-1]a[5]a.length = 5 but NO a[5] → ArrayIndexOutOfBoundsException
  • Valid indices run from 0 to length − 1; negative indices and length itself are invalid.
  • The compiler doesn't catch this; the program stops at run time with ArrayIndexOutOfBoundsException.
The loop condition must be i < arr.length; <= runs one pass too many.

Access · Step through the code

Code Trace: One Pass Too Many (<=)

0418263nonea

An array of length 3: valid indices 0, 1, 2.

0418263nonea▲ i

0 <= 3 → true, enter the body.

0418263nonea▲ i

a[0] = 4 is printed.

0418263nonea▲ i

i++ → 1 <= 3 → true, enter the body.

0418263nonea▲ i

a[1] = 8 is printed.

0418263nonea▲ i

i++ → 2 <= 3 → true, enter the body.

0418263nonea▲ i

a[2] = 6 is printed.

0418263nonea▲ i

i++ → 3 <= 3 → true. Careful: 3 is an invalid index, yet the condition holds!

0418263nonea▲ i

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

070188290scores

The array is ready; the index i will start at 0.

070188290▲ iscores

int i = 0; 0 < 3 → true

070188290▲ iscores

scores[0] = 70; %d: %d format gives 0: 70.

070188290▲ iscores

i++ → 1 < 3 → true

070188290▲ iscores

scores[1] = 88; %d: %d format gives 1: 88.

070188290▲ iscores

i++ → 2 < 3 → true

070188290▲ iscores

scores[2] = 90; %d: %d format gives 2: 90.

070188290scoresi = 3

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)

070188290scores

The enhanced for hands out the elements in order; there is no index.

070188290scoresscore70copy

Pass 1: score gets a copy of scores[0] (70).

070188290scoresscore75copy

score = 75; the array cell stays 70: only the copy changed.

070188290scoresscore75copy

75 is printed.

070188290scoresscore88copy

Pass 2: score gets a copy of scores[1] (88).

070188290scoresscore93copy

score = 93; the array cell stays 88: only the copy changed.

070188290scoresscore93copy

93 is printed.

070188290scoresscore90copy

Pass 3: score gets a copy of scores[2] (90).

070188290scoresscore95copy

score = 95; the array cell stays 90: only the copy changed.

070188290scoresscore95copy

95 is printed.

070188290scores

No elements left → the loop ends; score goes out of scope.

070188290scores

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

04172236nums

A four-element array.

04172236numssum0

The accumulator starts at sum = 0.

04172236numssum4

value = 4 → sum += value: 0 + 4 = 4.

04172236numssum11

value = 7 → sum += value: 4 + 7 = 11.

04172236numssum13

value = 2 → sum += value: 11 + 2 = 13.

04172236numssum19

value = 6 → sum += value: 13 + 6 = 19.

04172236numssum19

The loop is done. avg starts at 0 (a safe value for an empty array).

04172236numssum19

4 > 0 → true: the array isn't empty, so dividing is safe.

04172236numssum19

(double) 19 / 4 = 4.75. Without the cast, integer division would give 4.

04172236numssum19

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

05132931nums

Array: 5, 3, 9, 1.

05132931▲ minmaxnums

The first element is the candidate for both min and max (starting at 0 would fail for all-negative or all-positive arrays).

05132931▲ minmaxnums

Pass 1: value = 5.

05132931▲ minmaxnums

5 < 5 → false; min unchanged.

05132931▲ minmaxnums

5 > 5 → false; max unchanged.

05132931▲ minmaxnums

Pass 2: value = 3.

05132931▲ min▲ maxnums

3 < 5 → true: min = 3.

05132931▲ min▲ maxnums

3 > 5 → false; max unchanged.

05132931▲ min▲ maxnums

Pass 3: value = 9.

05132931▲ min▲ maxnums

9 < 3 → false; min unchanged.

05132931▲ min▲ maxnums

9 > 5 → true: max = 9.

05132931▲ min▲ maxnums

Pass 4: value = 1.

05132931▲ min▲ maxnums

1 < 3 → true: min = 1.

05132931▲ min▲ maxnums

1 > 9 → false; max unchanged.

05132931▲ min▲ maxnums

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)

0112233445arr

The array to reverse.

0112233445▲ left▲ rightarr

Two pointers: left = 0 and right = length − 1 = 4.

0112233445▲ left▲ rightarr

0 < 4 → true, so the ends get swapped.

0112233445▲ left▲ rightarrtmp1

tmp = arr[0] = 1: the left value is saved so it isn't lost.

0512233445▲ left▲ rightarrtmp1

arr[0] = arr[4] → 5 goes into the left cell.

0512233441▲ left▲ rightarrtmp1

arr[4] = tmp → 1 goes into the right cell. Swap done.

0512233441▲ left▲ rightarr

The pointers move inward: left = 1, right = 3.

0512233441▲ left▲ rightarr

1 < 3 → true, so the ends get swapped.

0512233441▲ left▲ rightarrtmp2

tmp = arr[1] = 2: the left value is saved so it isn't lost.

0514233441▲ left▲ rightarrtmp2

arr[1] = arr[3] → 4 goes into the left cell.

0514233241▲ left▲ rightarrtmp2

arr[3] = tmp → 2 goes into the right cell. Swap done.

0514233241▲ leftrightarr

The pointers move inward: left = 2, right = 2.

0514233241▲ leftrightarr

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

060175290345480grades

Five students' grades. First the average, then those above it: two passes are needed.

060175290345480grades

Pass 1: accumulate the sum.

060175290345480grades

x = 60 → sum = 60.

060175290345480grades

x = 75 → sum = 135.

060175290345480grades

x = 90 → sum = 225.

060175290345480grades

x = 45 → sum = 270.

060175290345480grades

x = 80 → sum = 350.

060175290345480gradesavg70.0

(double) 350 / 5 = 70.0.

060175290345480gradesavg70.0

Counter for pass 2: above = 0.

060175290345480gradesavg70.0

60 > 70.0 → false.

060175290345480gradesavg70.0✓

75 > 70.0 → true: above = 1.

060175290345480gradesavg70.0✓✓

90 > 70.0 → true: above = 2.

060175290345480gradesavg70.0✓✓

45 > 70.0 → false.

060175290345480gradesavg70.0✓✓✓

80 > 70.0 → true: above = 3.

060175290345480gradesavg70.0✓✓✓

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

071122531249alargestMINsecondMIN

Both candidates start at the smallest int (Integer.MIN_VALUE); each element is examined once.

071122531249alargest7secondMIN

7 > MIN → new largest: the old largest (MIN) drops to second, largest = 7.

071122531249alargest12second7

12 > 7 → new largest: the old largest (7) drops to second, largest = 12.

071122531249alargest12second7

No change: 5 is not greater than second (7).

071122531249alargest12second7

No change: 12 == largest (a repeat) doesn't count.

071122531249alargest12second9

9 is smaller than the largest but greater than second, and 9 != 12 → second = 9.

071122531249alargest12second9

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

rolls36316300102030405060count

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.

rolls36316300102031405060count

die = 3 → count[3]++ → 1. No if-else chain needed!

rolls36316300102031405061count

die = 6 → count[6]++ → 1. No if-else chain needed!

rolls36316300102032405061count

die = 3 → count[3]++ → 2. No if-else chain needed!

rolls36316300112032405061count

die = 1 → count[1]++ → 1. No if-else chain needed!

rolls36316300112032405062count

die = 6 → count[6]++ → 2. No if-else chain needed!

rolls36316300112033405062count

die = 3 → count[3]++ → 3. No if-else chain needed!

rolls36316300112033405062count

y = 1: count[1] = 1 star.

rolls36316300112033405062count

y = 2: count[2] = 0 stars (none).

rolls36316300112033405062count

y = 3: count[3] = 3 stars.

rolls36316300112033405062count

y = 4: count[4] = 0 stars (none).

rolls36316300112033405062count

y = 5: count[5] = 0 stars (none).

rolls36316300112033405062count

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)

01234567891011121314151617181920crossed out: composite[i] = true

All cells false: initially 2…20 are all prime candidates.

01234567891011121314151617181920crossed out: composite[i] = true

2 × 2 = 4 <= 20 → true.

01234567891011121314151617181920crossed out: composite[i] = 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.

01234567891011121314151617181920crossed out: composite[i] = true

3 × 3 = 9 <= 20 → true.

01234567891011121314151617181920crossed out: composite[i] = true

3 is not crossed out → prime. Its multiples are marked starting from 3·3: k = 9, 12, 15, 18.

01234567891011121314151617181920crossed out: composite[i] = true

4 × 4 = 16 <= 20 → true.

01234567891011121314151617181920crossed out: composite[i] = true

composite[4] = true → 4 is already crossed out; no need to visit its multiples.

01234567891011121314151617181920crossed out: composite[i] = true

5 × 5 = 25 <= 20 → false: no need to look for divisors above √20.

012✓3✓45✓67✓891011✓1213✓14151617✓1819✓20crossed out: composite[i] = true

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 = a copies the reference, not the elements: two arrows point to the same object.
  • For an independent copy use a.clone(), Arrays.copyOf(a, a.length) or System.arraycopy.
  • For arrays of objects these copy the element references; the objects themselves are not duplicated (shallow copy).
StackHeapabc011223011223b = a → same objectc = a.clone() → new object

Operations · Step through the code

Code Trace: Copying a Reference vs. Copying Elements

Stack (variables)Heap (objects)011223a

One array on the heap; a refers to it.

Stack (variables)Heap (objects)011223ab

b = a: no new array is created; b gets the same reference → two arrows on one object.

Stack (variables)Heap (objects)0991223ab

b[0] = 99: the object b refers to changed, and it is a's object too!

Stack (variables)Heap (objects)0991223ab

a[0] is now 99. A copied reference is not an independent array.

Stack (variables)Heap (objects)09912230991223copyabc

a.clone() creates a new array on the heap and copies the elements one by one.

Stack (variables)Heap (objects)099122309915023copyabc

c[1] = 50 changes only the copy.

Stack (variables)Heap (objects)099122309915023copyabc

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}};
CallResult
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]
  • == and equals compare references; for contents use Arrays.equals (deepEquals for 2D).
  • copyOf pads with zeros if the length is larger and truncates if smaller; in copyOfRange the 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));
iarr[i]== 6 ?
08false
13false
26true → return 2
  • Output: 2. The loop ends early at the first match.
  • The parameter arr refers to the same array as d (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;.
before52917Arrays.sort(a)after (sorted in place)0112253749Arrays.binarySearch(a, 7) → 3

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.sort changes 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
odd count (n = 5), sorted0113253749s[n / 2] = s[2] → 5even count (n = 4), sorted02132638(s[1] + s[2]) / 2.0 → 4.5

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;
    }
  }
}
passarray after passcomp.swap
1[1, 4, 2, 5]33
2[1, 2, 4, 5]21
3[1, 2, 4, 5]10
  • 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;
}
ikeyshifted rightarray after pass
134[3, 4, 5, 1]
25—[3, 4, 5, 1]
315, 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);
passlohimida[mid]decision
10731212 < 23 → lo = 4
247523found: 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));
passlohimida[mid]decision
103144 < 5 → lo = 2
223266 > 5 → hi = 1
—21lo > 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.binarySearch returns the same value.

Analysis

Basic Complexities

OperationTime
Index accessO(1)
Linear searchO(n)
Traverse to the endO(n)
Insert / delete in the middleO(n)
Two nested full traversalsO(n²)
Insert 4 at 1; the rest shift right:031825364after:0314283546number of shifts ≈ n → 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.
StackHeapmatrixrows00112231041526matrix[1][2] → 6

Matrices · Step through the code

A Jagged Array: new int[3][]

StackHeapmouter array0null1null2null

new int[3][] creates only the outer array (3 cells). The rows don't exist yet: all three cells are null.

StackHeapmouter array001null2null

m[0] = new int[1]: the first cell points to a one-element row. m[1] and m[2] are still null.

StackHeapmouter array001002null

m[1] = new int[2]: the second row has 2 elements.

StackHeapmouter array001002000

m[2] = new int[3]: the rows differ in length, which makes a jagged array. Each row is a separate object.

StackHeapmouter array00length = 11002000

i = 0: m[0].length = 1 is printed.

StackHeapmouter array00length = 1100length = 22000

i = 1: m[1].length = 2 is printed.

StackHeapmouter array00length = 1100length = 22000length = 3

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

StackHeapa1234

a is an outer array pointing to two row arrays.

StackHeapa1234brows are shared

a.clone() copies only the outer array: both outer arrays point to the same row objects (shallow copy).

StackHeapa99234brows are shared

b[0][0] = 99: b[0] and a[0] are the same row → a[0][0] is 99 too.

StackHeapa99234b78new rowa[0] = b[0] (shared)

b[1] = new int[]{7, 8} only points b's cell at a new row; a[1] is unchanged.

StackHeapa99234b78new rowa[0] = b[0] (shared)

a: shared row 0 changed (99); row 1 is still {3, 4}.

StackHeapa99234b78new rowa[0] = b[0] (shared)

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

00112231456i ↓ j →

A matrix of 2 rows × 3 columns; matrix.length = 2.

00112231456i ↓ j →

Outer loop: 0 < 2 → true → process row 0.

00112231456i ↓ j →

Inner loop: 0 < 3 → true; prints matrix[0][0] = 1 (print stays on the line).

00112231456i ↓ j →

Inner loop: 1 < 3 → true; prints matrix[0][1] = 2 (print stays on the line).

00112231456i ↓ j →

Inner loop: 2 < 3 → true; prints matrix[0][2] = 3 (print stays on the line).

00112231456i ↓ j →

3 < 3 → false: the row is done; leave the inner loop.

00112231456i ↓ j →

println() moves to the next line; then i++.

00112231456i ↓ j →

Outer loop: 1 < 2 → true → process row 1.

00112231456i ↓ j →

Inner loop: 0 < 3 → true; prints matrix[1][0] = 4 (print stays on the line).

00112231456i ↓ j →

Inner loop: 1 < 3 → true; prints matrix[1][1] = 5 (print stays on the line).

00112231456i ↓ j →

Inner loop: 2 < 3 → true; prints matrix[1][2] = 6 (print stays on the line).

00112231456i ↓ j →

3 < 3 → false: the row is done; leave the inner loop.

00112231456i ↓ j →

println() moves to the next line; then i++.

00112231456i ↓ j →

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

00112231456matrix (2×3)

The source matrix is 2 × 3.

00112231456matrix (2×3)

matrix.length = number of rows = 2.

00112231456matrix (2×3)

matrix[0].length = length of the first row = 3.

00112231456matrix (2×3)00010100200t (3×2)

The target t has the dimensions swapped: 3 × 2, all cells 0.

00112231456matrix (2×3)00110100200t (3×2)

t[0][0] = matrix[0][0] = 1: rows ↔ columns swap.

00112231456matrix (2×3)00110120200t (3×2)

t[1][0] = matrix[0][1] = 2: rows ↔ columns swap.

00112231456matrix (2×3)00110120230t (3×2)

t[2][0] = matrix[0][2] = 3: rows ↔ columns swap.

00112231456matrix (2×3)00114120230t (3×2)

t[0][1] = matrix[1][0] = 4: rows ↔ columns swap.

00112231456matrix (2×3)00114125230t (3×2)

t[1][1] = matrix[1][1] = 5: rows ↔ columns swap.

00112231456matrix (2×3)00114125236t (3×2)

t[2][1] = matrix[1][2] = 6: rows ↔ columns swap.

00112231456matrix (2×3)00114125236t (3×2)

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)

1234A×5678B=0000C

C[i][j] = the sum of products of row i of A and column j of B. C starts as zeros.

1234A×5678B=5000CA[0][0] × B[0][0]= 1 × 5 = 5

C[0][0] += 1 × 5 → 0 + 5 = 5

1234A×5678B=19000CA[0][1] × B[1][0]= 2 × 7 = 14

C[0][0] += 2 × 7 → 5 + 14 = 19 (cell done)

1234A×5678B=19600CA[0][0] × B[0][1]= 1 × 6 = 6

C[0][1] += 1 × 6 → 0 + 6 = 6

1234A×5678B=192200CA[0][1] × B[1][1]= 2 × 8 = 16

C[0][1] += 2 × 8 → 6 + 16 = 22 (cell done)

1234A×5678B=1922150CA[1][0] × B[0][0]= 3 × 5 = 15

C[1][0] += 3 × 5 → 0 + 15 = 15

1234A×5678B=1922430CA[1][1] × B[1][0]= 4 × 7 = 28

C[1][0] += 4 × 7 → 15 + 28 = 43 (cell done)

1234A×5678B=19224318CA[1][0] × B[0][1]= 3 × 6 = 18

C[1][1] += 3 × 6 → 0 + 18 = 18

1234A×5678B=19224350CA[1][1] × B[1][1]= 4 × 8 = 32

C[1][1] += 4 × 8 → 18 + 32 = 50 (cell done)

1234A×5678B=19224350C

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 ArrayList are more convenient.
  • int[] stores the numbers directly; ArrayList<Integer> wraps each number in an object.
  • Choose based on usage, readability and measured performance.
A full array doesn't grow:3856+ 7 ?new, larger array + copying38567ArrayList does this for you.

Verification

Common Mistakes

One pass too many

i <= a.length reaches a[length] on the last pass → ArrayIndexOutOfBoundsException. Use i < a.length.

First element of an empty array

int min = a[0]; fails on an empty array; check a.length == 0 first.

Copying the reference

int[] b = a; is not a new array; b[0] = 9 changes a too. Use a.clone() for a copy.

Jagged matrices

Not every row has length matrix[0].length; use matrix[i].length in the inner loop.

i <= a.length → a[5] at the end3081126324✗5a.length = 5 → valid indices 0 … 4int[] b = a; b[0] = 9;ab923one array: a[0] becomes 9 too

Summary

Chapter Summary

Structure

A fixed number of elements of one type; indices 0 … length − 1; the variable refers to the array.

Access

a[i] reads and writes in constant time; an out-of-bounds index is a run-time error.

Traversal

Classic for (when you need the index) and enhanced for (assigning to the loop variable leaves the array alone); sum, min-max, reversing, searching.

Matrices

int[][] is an array of arrays: matrix.length rows, matrix[i].length columns.

Summary

Review Questions

  1. What is the last index of a five-element array?
  2. When is the enhanced for not enough?
  3. What is the difference between assigning an array and copying its elements?
  4. What precondition does binary search require?
  5. What do matrix.length and matrix[0].length give?
Answers
  1. 4 (length − 1).
  2. When you need the index: printing positions, writing a new value to a cell, traversing backward or walking two arrays together.
  3. Assignment (b = a) copies only the reference, so both variables refer to one object; clone/Arrays.copyOf create a new array.
  4. The array must be sorted.
  5. The number of rows and the number of columns of the first row.

Summary

Exercises

  1. Write code that finds the count and sum of the even numbers in an int[].
  2. Write code that rotates an array one position right (last element first) with no extra array: {1,2,3,4} → {4,1,2,3}.
  3. Merge two sorted arrays into a single sorted array ({1,4,7} + {2,3,9}).
  4. Add a boolean flag to bubble sort that stops early when a pass makes no swaps.
  5. Use the sieve of Eratosthenes to count the primes up to 100 (answer: 25).
  6. 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.

The End

Chapter 10: Arrays
Previous: Chapter 9: Methods · Next: Chapter 11: Strings
1 / 1Sercan KÜLCÜ. All rights reserved.