Home › Learn › Java › Arrays and lists

Arrays

Lesson 16 of 40. A fixed-length row of values of one type.

An array holds a fixed number of values of one type: int[] scores = {90, 72, 85}; or new int[5] for five zeros. scores[0] is the first value, scores.length the count (no parentheses), and an index outside 0 to length - 1 is an error. A for loop over i from 0 to length - 1 visits every slot: for (int i = 0; i < scores.length; i++).

Arrays of strings work the same way, but compare the elements with .equals. A method can return an array it built: int[] result = new int[n]; ... return result;.

The library project will need to find a book by its title in an array of titles; the class Search in this lesson does that with a plain loop.

int[] scores = {90, 72, 85};
int total = 0;
for (int i = 0; i < scores.length; i++) {
    total += scores[i];
}
System.out.println(total / scores.length);   // 82

Your task

In Main, write static int sum(int[] xs) returning the total of the values, static int max(int[] xs) returning the largest (assume at least one value), and static int[] squares(int n) returning a new array of 1*1, 2*2, ..., n*n.

In the class Search, write static int indexOf(String[] items, String wanted) returning the index of the first element equal to wanted, or -1 when it is not there.

Part of the final project. Search finds the position of a title in the catalog, or -1 when it is not there. It is saved in this browser and loaded into Project: the library when you get there.

Hint 1

max: start with int best = xs[0]; then for each value, if (xs[i] > best) best = xs[i];

Hint 2

squares: result[i] = (i + 1) * (i + 1). indexOf: for (int i = 0; i < items.length; i++) if (items[i].equals(wanted)) return i; then return -1 after the loop.

Show the solution
public class Main {
    static int sum(int[] xs) {
        int total = 0;
        for (int i = 0; i < xs.length; i++) {
            total += xs[i];
        }
        return total;
    }

    static int max(int[] xs) {
        int best = xs[0];
        for (int i = 1; i < xs.length; i++) {
            if (xs[i] > best) {
                best = xs[i];
            }
        }
        return best;
    }

    static int[] squares(int n) {
        int[] result = new int[n];
        for (int i = 0; i < n; i++) {
            result[i] = (i + 1) * (i + 1);
        }
        return result;
    }

    public static void main(String[] args) {
        int[] scores = {90, 72, 85};
        System.out.println(sum(scores) + " " + max(scores));
    }
}

class Search {
    static int indexOf(String[] items, String wanted) {
        for (int i = 0; i < items.length; i++) {
            if (items[i].equals(wanted)) {
                return i;
            }
        }
        return -1;
    }
}

    Compiles with OpenJDK javac and TeaVM, both compiled to WebAssembly (7 MB download the first time, then cached), and runs in this tab; nothing is sent anywhere.