BeginnerJava · Lesson 5 of 8

Arrays & Strings

Create and process arrays, use the Arrays helper class, and build text with StringBuilder.

An array holds a fixed number of values of one type: int[] scores = {78, 64, 91};. Indexes start at 0, and scores.length gives the size. Accessing an index outside the array throws an ArrayIndexOutOfBoundsException.

The java.util.Arrays class sorts, searches, fills, copies and prints arrays. Two-dimensional arrays (int[][]) model tables such as a timetable or a marks sheet.

Strings are immutable — every change creates a new String. Useful methods include split, contains, substring, replace, charAt and join. When building text in a loop, use StringBuilder for efficiency.

ArraysDemo.javaJava
import java.util.Arrays;

public class ArraysDemo {
    public static void main(String[] args) {
        int[] scores = {78, 64, 91, 45, 88};
        String[] names = {"Neema", "Amina", "Juma", "Baraka", "Rehema"};

        int best = scores[0];
        for (int s : scores) best = Math.max(best, s);
        System.out.println("Best: " + best);

        int[] sorted = Arrays.copyOf(scores, scores.length);
        Arrays.sort(sorted);
        System.out.println(Arrays.toString(sorted));          // [45, 64, 78, 88, 91]
        System.out.println(Arrays.stream(scores).average().orElse(0));

        Arrays.sort(names);
        System.out.println(String.join(", ", names));

        int[][] marks = {
            {88, 79, 91},   // Amina: Maths, Biology, English
            {42, 55, 61},   // Juma
        };
        for (int row = 0; row < marks.length; row++) {
            int total = 0;
            for (int mark : marks[row]) total += mark;
            System.out.println("Row " + row + " total: " + total);
        }

        String line = "Amina Hassan,4,A,88";
        String[] parts = line.split(",");
        System.out.println(parts[0].toUpperCase() + " | form " + parts[1] + " | starts with A? " + parts[0].startsWith("A"));

        StringBuilder report = new StringBuilder();
        for (int i = 0; i < names.length; i++) {
            report.append(i + 1).append(". ").append(names[i]).append('\n');
        }
        System.out.print(report);
    }
}

Key points

  • Arrays have a fixed size; indexes run from 0 to length - 1.
  • Use java.util.Arrays for sorting, copying and printing.
  • Strings are immutable; build text in loops with StringBuilder.

Exercise

Store a week of daily temperatures in an array. Print the highest, lowest and average, the days above average, and a simple bar chart using "*".repeat(n).

Show solution

Try the exercise yourself first — then compare your approach with this one.

One pass finds the highest, lowest and total. A second pass, which needs the average, prints the days above it. "*".repeat(n) draws each bar, scaled down so it fits on screen.

Temperatures.javaJava
public class Temperatures {
    public static void main(String[] args) {
        String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
        int[] temps = {28, 31, 30, 33, 29, 27, 32};

        int highest = temps[0], lowest = temps[0], total = 0;
        for (int t : temps) {
            highest = Math.max(highest, t);
            lowest = Math.min(lowest, t);
            total += t;
        }
        double average = (double) total / temps.length;
        System.out.printf("Highest %d, lowest %d, average %.1f%n", highest, lowest, average);

        StringBuilder above = new StringBuilder();
        for (int i = 0; i < temps.length; i++) {
            if (temps[i] > average) above.append(days[i]).append(' ');
        }
        System.out.println("Above average: " + above.toString().strip());

        for (int i = 0; i < temps.length; i++) {
            System.out.printf("%s %s %d%n", days[i], "*".repeat(temps[i] - 20), temps[i]);
        }
    }
}

Check your understanding

  1. What is the last valid index of an array with 5 elements?

  2. Which class sorts and prints arrays for you?

  3. Why use a StringBuilder when building text in a loop?

  4. What does "Amina,4,88".split(",") return?

Ask AI