← Back to Java series
πŸ“¦
Collections & Generics
Collections & Generics Β· Prerequisite: previous lecture

11. Arrays

An **array** is the most basic data structure for accessing values of the same type by **contiguous index**. Its size is fixed once allocated, but it's fast and memory-efficient.

JavaCollectionsGenericsarray
Duration
⏱ ~1-1.5 hours
Level
πŸ“Š Intermediate
Prerequisite
🎯 Previous lecture or equivalent knowledge
OUTCOME
An **array** is the most basic data structure for accessing values of the same type by **contiguous index**. Its size is fixed once allocated, but it's fast and memory-efficient.

What you'll learn

  • 1Declare, initialize, and access 1D and 2D arrays
  • 2Iterate with `for` and enhanced for
  • 3Use utilities like `Arrays.toString` / `sort` / `copyOf`
  • 4Understand the difference between `int[]` (primitive) and `Integer[]` (object)

Overview

An **array** is the most basic data structure for accessing values of the same type by **contiguous index**. Its size is fixed once allocated, but it's fast and memory-efficient.

Core Concepts

1) 1D arrays

java
int[] nums = new int[5];         // {0,0,0,0,0}
nums[0] = 10;
String[] colors = {"red", "green", "blue"};
System.out.println(colors.length);   // 3

`length` is a **field**, not a method (no parentheses).

2) 2D arrays

java
int[][] mat = {
    {1, 2, 3},
    {4, 5, 6}
};
System.out.println(mat[1][2]);   // 6
System.out.println(mat.length);     // 2 (rows)
System.out.println(mat[0].length);  // 3 (cols)

Java's 2D arrays are **arrays of arrays**. Rows can differ in length (jagged arrays).

3) `Arrays` utility

java
import java.util.Arrays;

int[] a = {3, 1, 4, 1, 5, 9, 2};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
int[] copy = Arrays.copyOf(a, 5);

4) Primitive vs object array

java
int[] xs = new int[3];        // defaults to 0
Integer[] ys = new Integer[3]; // defaults to null

`int[]` is fast and compact but cannot be passed directly to `List<Integer>`.

Examples

Example 1 β€” `Array1D.java`: 1D basics

java
public class Array1D {
    public static void main(String[] args) {
        int[] nums = new int[5];
        for (int i = 0; i < nums.length; i++) nums[i] = (i + 1) * 10;

        for (int n : nums) System.out.print(n + " ");
        System.out.println();
        System.out.println("length=" + nums.length);
    }
}

**Output**

text
10 20 30 40 50
length=5

**Note:** indices start at 0. Out-of-range β†’ `ArrayIndexOutOfBoundsException`.

Example 2 β€” `Array2D.java`: 2D

java
public class Array2D {
    public static void main(String[] args) {
        int[][] mat = {
            {1, 2, 3},
            {4, 5, 6}
        };
        for (int r = 0; r < mat.length; r++) {
            for (int c = 0; c < mat[r].length; c++) {
                System.out.print(mat[r][c] + " ");
            }
            System.out.println();
        }
    }
}

**Output**

text
1 2 3
4 5 6 

**Note:** access by row index first, then column.

Example 3 β€” `ArraysUtil.java`: sort / copy / toString

java
import java.util.Arrays;

public class ArraysUtil {
    public static void main(String[] args) {
        int[] a = {3, 1, 4, 1, 5, 9, 2, 6};
        Arrays.sort(a);
        System.out.println(Arrays.toString(a));

        int[] head = Arrays.copyOf(a, 4);
        System.out.println(Arrays.toString(head));

        int[] slice = Arrays.copyOfRange(a, 2, 6);
        System.out.println(Arrays.toString(slice));
    }
}

**Output**

text
[1, 1, 2, 3, 4, 5, 6, 9]
[1, 1, 2, 3]
[2, 3, 4, 5]

**Note:** `copyOfRange(from, to)` β€” `to` is **exclusive**.

Example 4 β€” `IntVsInteger.java`: primitive vs boxed

java
import java.util.Arrays;
import java.util.List;

public class IntVsInteger {
    public static void main(String[] args) {
        int[] xs = new int[3];               // defaults to 0
        Integer[] ys = new Integer[3];        // defaults to null
        System.out.println("xs[0]=" + xs[0]);
        System.out.println("ys[0]=" + ys[0]);

        Integer[] zs = {1, 2, 3};
        List<Integer> list = Arrays.asList(zs);
        System.out.println(list);
    }
}

**Output**

text
xs[0]=0
ys[0]=null
[1, 2, 3]

**Note:** `Arrays.asList` returns a **fixed-size List** β€” `.add` throws.

Common Mistakes

  1. Calling `nums.length()` like a method β€” it's a field
  2. Index-out-of-bounds β†’ `ArrayIndexOutOfBoundsException`
  3. Assuming rows are all the same length (they can be jagged)
  4. The `Arrays.asList(int[])` trap β†’ becomes `List<int[]>` (use `IntStream` for primitive arrays)
  5. Comparing arrays with `==` (use `Arrays.equals` or `Arrays.deepEquals`)

Summary

  • Arrays are fast, fixed-size data structures
  • Indices: 0..length-1
  • Most utilities live as static methods on `Arrays`
  • If you need a resizable collection, use `List` (next lecture)

Practice

# Practice - 11. Arrays

## Exercise 1 β€” Sum, max, average

  • File: `Homework01.java`
  • Key concepts: enhanced for, accumulation

Requirements

  • Given `{3, 7, 1, 9, 4}`, print the sum, max, and average (2 decimal places).

Expected output

text
sum=24
max=9
avg=4.80

## Exercise 2 β€” Matrix transpose

  • File: `Homework02.java`
  • Key concepts: 2D array, index swap

Requirements

  • Transpose a 2x3 matrix into a 3x2 matrix and print it.

Expected output

text
original
1 2 3
4 5 6
transposed
1 4
2 5
3 6 

## Solutions After trying it yourself, compare with [`answer/`](./answer/).

Solution code (homework/answer/)

answer/Homework01.java

java
/** Sum, max, average. */
public class Homework01 {
    public static void main(String[] args) {
        int[] arr = {3, 7, 1, 9, 4};
        int sum = 0;
        int max = arr[0];
        for (int n : arr) {
            sum += n;
            if (n > max) max = n;
        }
        double avg = (double) sum / arr.length;
        System.out.println("sum=" + sum);
        System.out.println("max=" + max);
        System.out.printf("avg=%.2f%n", avg);
    }
}

answer/Homework02.java

java
/** Matrix transpose. */
public class Homework02 {
    public static void main(String[] args) {
        int[][] mat = { {1, 2, 3}, {4, 5, 6} };

        System.out.println("original");
        print(mat);

        int[][] t = new int[mat[0].length][mat.length];
        for (int r = 0; r < mat.length; r++) {
            for (int c = 0; c < mat[r].length; c++) {
                t[c][r] = mat[r][c];
            }
        }
        System.out.println("transposed");
        print(t);
    }

    static void print(int[][] m) {
        for (int[] row : m) {
            for (int v : row) System.out.print(v + " ");
            System.out.println();
        }
    }
}

Try It Yourself

bash
cd 03_collections/11_array/src
javac ArraysUtil.java
java ArraysUtil

Next Lecture

[12_List_Set_Map](../12_List_Set_Map/) β€” the three most common collection interfaces.

Example code / lecture materials

All lecture materials and example code are openly available on GitHub.

View on GitHub β†—