Methods, Arrays & Strings

Iterating & Manipulating Arrays

15 min Lesson 6 of 14

Iterating & Manipulating Arrays

You already know how to declare and fill an array. Now comes the practical skill: walking through every element to read, modify, or search it, and using the built-in java.util.Arrays utility class so you do not have to re-implement common operations from scratch.

Looping Over Arrays

Java gives you three natural ways to loop over an array. Understanding when to use each one is what separates readable code from messy code.

1. Classic for loop — use this when you need the index (position number).

int[] scores = {85, 92, 78, 90, 88}; for (int i = 0; i < scores.length; i++) { System.out.println("Student " + (i + 1) + " scored " + scores[i]); }

scores.length always returns the total number of elements. Notice the condition is i < scores.length, not i <= scores.length — valid indices run from 0 to length - 1.

ArrayIndexOutOfBoundsException is the most common beginner mistake with arrays. It happens the moment you try to access index scores.length or any negative index. Always double-check your loop boundary.

2. Enhanced for loop (for-each) — use this when you only need the value, not the position.

for (int score : scores) { System.out.println("Score: " + score); }

This reads as "for each score in scores". It is shorter and eliminates the off-by-one risk entirely. The trade-off is that you cannot modify the array through the loop variable — changes to score inside the loop do not affect the original array.

3. Modifying elements — you must use the index form.

// Double every score for (int i = 0; i < scores.length; i++) { scores[i] = scores[i] * 2; }
Rule of thumb: if you need to read elements, prefer the enhanced for loop — it is cleaner. If you need to write to elements or need the index for any reason, use the classic for loop.

The Arrays Utility Class

The java.util.Arrays class ships with the JDK and provides ready-made, highly optimised methods for the most common array tasks. Import it once at the top of your file:

import java.util.Arrays;

Arrays.toString — Printing an Array

If you try System.out.println(scores) directly, Java prints something like [I@6d06d69c — a memory address, not the values. Arrays.toString() gives you a readable representation:

int[] numbers = {3, 1, 4, 1, 5, 9, 2, 6}; System.out.println(Arrays.toString(numbers)); // Output: [3, 1, 4, 1, 5, 9, 2, 6]

Arrays.sort — Sorting an Array

Arrays.sort() sorts an array in place (it modifies the original array). For primitive types it uses a dual-pivot quicksort — extremely fast in practice.

int[] numbers = {3, 1, 4, 1, 5, 9, 2, 6}; Arrays.sort(numbers); System.out.println(Arrays.toString(numbers)); // Output: [1, 1, 2, 3, 4, 5, 6, 9]

You can also sort a sub-range without touching the rest of the array:

// Sort only indices 2 to 4 (inclusive start, exclusive end) int[] data = {50, 40, 30, 20, 10, 60}; Arrays.sort(data, 2, 5); System.out.println(Arrays.toString(data)); // Output: [50, 40, 10, 20, 30, 60]

Arrays.fill — Setting All Elements to One Value

Instead of looping manually to initialise every cell, Arrays.fill() does it in one call:

int[] grid = new int[5]; Arrays.fill(grid, -1); System.out.println(Arrays.toString(grid)); // Output: [-1, -1, -1, -1, -1]

Arrays.copyOf — Creating a Resized Copy

Arrays.copyOf(original, newLength) creates a brand-new array. If newLength is larger than the original, the extra slots are zero-filled; if smaller, the result is truncated.

int[] original = {10, 20, 30}; // Grow the array int[] grown = Arrays.copyOf(original, 5); System.out.println(Arrays.toString(grown)); // Output: [10, 20, 30, 0, 0] // Shrink the array int[] shrunk = Arrays.copyOf(original, 2); System.out.println(Arrays.toString(shrunk)); // Output: [10, 20]
Why copy instead of just resizing? Arrays in Java have a fixed length once created — you cannot change original.length after the fact. Arrays.copyOf() is the standard pattern to "resize" an array by producing a new one with the data you want.

Arrays.binarySearch — Searching a Sorted Array

Once an array is sorted, you can search it in O(log n) time with binary search instead of scanning every element:

int[] sorted = {1, 3, 5, 7, 9, 11}; int index = Arrays.binarySearch(sorted, 7); System.out.println("Found 7 at index: " + index); // Output: Found 7 at index: 3

If the value is not found, binarySearch returns a negative number. The array must already be sorted before you call this method — calling it on an unsorted array gives unpredictable results.

Always sort before searching. A common mistake is calling Arrays.binarySearch() on an unsorted array and getting a wrong or negative result. If you are unsure whether the array is sorted, call Arrays.sort() first.

Putting It All Together — A Small Example

import java.util.Arrays; public class ArrayDemo { public static void main(String[] args) { int[] temps = {28, 15, 33, 22, 18, 29, 11}; // Find min and max with a loop int min = temps[0]; int max = temps[0]; for (int t : temps) { if (t < min) min = t; if (t > max) max = t; } System.out.println("Min: " + min + ", Max: " + max); // Sort and print Arrays.sort(temps); System.out.println("Sorted: " + Arrays.toString(temps)); // Search for value 22 int pos = Arrays.binarySearch(temps, 22); System.out.println("22 is at index: " + pos); } } // Min: 11, Max: 33 // Sorted: [11, 15, 18, 22, 28, 29, 33] // 22 is at index: 3

Summary

Use the classic for loop when you need the index; use the enhanced for-each when you only need values. The Arrays utility class gives you sort, fill, copyOf, toString, and binarySearch — all optimised and tested, so prefer them over writing your own loops for these tasks. In the next lesson you will step up to multidimensional arrays and see how these same tools apply to rows and columns of data.