🌱BeginnerArrays

Arrays

Store multiple values of the same type in a fixed-size array - declare, initialise, access, and iterate.

Overview

An array is a fixed-size container that holds multiple values of the same type. Instead of declaring ten separate int variables, you declare one int array of length 10. Each element is accessed by its zero-based index (0 to length-1). Arrays in Java are objects. Once created, their size cannot change (unlike ArrayList). They are the foundation of most data processing - sorting, searching, summing, and transforming collections of values.

Key Points

  • •Declaration: `int[] nums;` - array type is type followed by []
  • •Creation: `new int[5]` - creates an array of 5 ints (default values: 0)
  • •Array literal: `int[] nums = {10, 20, 30};` - declares and initialises at once
  • •Access: `nums[0]` is the first element; `nums[nums.length - 1]` is the last
  • •Indices are zero-based: 0, 1, 2 ... length-1
  • •Accessing an out-of-bounds index throws ArrayIndexOutOfBoundsException
  • •Arrays have a fixed size - use ArrayList (J040) for a resizable list

Examples

Declaring, creating, and accessing arrays

public class Main {
    public static void main(String[] args) {
        // Declaration + creation (default values: 0)
        int[] scores = new int[5];
        scores[0] = 85;
        scores[1] = 92;
        scores[2] = 78;
        scores[3] = 95;
        scores[4] = 88;

        System.out.println("First: " + scores[0]);  // 85
        System.out.println("Last: " + scores[4]);   // 88
        System.out.println("Length: " + scores.length); // 5

        // Array literal
        String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri"};
        System.out.println(days[2]); // Wed
    }
}

Array length is .length (no parentheses), unlike String's .length() method.

Iterating over arrays

public class Main {
    public static void main(String[] args) {
        double[] prices = {9.99, 19.50, 4.75, 14.25, 7.00};
        double total = 0;

        // for-each - clean for processing all elements
        for (double price : prices) {
            total += price;
        }
        System.out.printf("Total: $%.2f%n", total);

        // Traditional for - when you need the index
        for (int i = 0; i < prices.length; i++) {
            System.out.printf("Item %d: $%.2f%n", i + 1, prices[i]);
        }
    }
}

Choose for-each for simple processing; use indexed for when you need to know the position.

Common array patterns

public class Main {
    public static void main(String[] args) {
        int[] data = {5, 2, 8, 1, 9, 3, 7};

        // Find max
        int max = data[0];
        for (int n : data) {
            if (n > max) max = n;
        }
        System.out.println("Max: " + max); // 9

        // Count elements meeting a condition
        int evenCount = 0;
        for (int n : data) {
            if (n % 2 == 0) evenCount++;
        }
        System.out.println("Even count: " + evenCount); // 2

        // Copy an array
        int[] copy = new int[data.length];
        for (int i = 0; i < data.length; i++) {
            copy[i] = data[i];
        }
    }
}

Use Arrays.copyOf() (J027) for a one-line copy instead of a manual loop.

Common Mistakes

  • ArrayIndexOutOfBoundsException: accessing index >= array.length or a negative index
  • Using .length() instead of .length - arrays use .length (no parentheses); only String has .length()
  • Forgetting arrays are zero-indexed: an array of length 5 has indices 0, 1, 2, 3, 4 - not 1, 2, 3, 4, 5

Note

Always initialise your array with a literal or explicit assignments. `new int[5]` creates an array filled with zeros, but relying on default values can make code less clear.

Exercises

Write Java code and click Run to execute it instantly. When your output looks correct, mark as done.

Loading editor…

Completed: 0 / 4 exercises

Knowledge Check

Question 1 of 4

What is the index of the last element in an array of length 5?