Java + Spring Boot track

Lesson 11 · Part 3: Collections & Generics

Arrays

Array is the most basic data structure that accesses values of the same type using consecutive indices. Once the size is set, it cannot be changed (fixed size), but…

Part 3: Collections & Generics3 min readFree lesson

Array is the most basic data structure that accesses values of the same type using consecutive indices. Once the size is set, it cannot be changed (fixed size), but it is fast and memory efficient.

Learning Objectives

  • Declare, initialize, and access one-dimensional and two-dimensional arrays
  • Traverse with for and enhanced for
  • Use utilities such as Arrays.toString / sort / copyOf
  • Know the difference between int[] (primitive) and Integer[] (object)

Key concepts

1) One-dimensional array

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) 2-dimensional array

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

A two-dimensional array in Java is an array of arrays. Each row may have a different length (jagged array).

3) Arrays utility

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 array vs object array

int[] xs = new int[3];        //Default 0
Integer[] ys = new Integer[3]; //default null

int[] is fast and has small memory, but it cannot be directly added to the collection (List<Integer>).

See as example

Example 1 — Array1D.java: One-dimensional array basics

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);
    }
}

Execution result

10 20 30 40 50 
length=5

Memo: The index starts from 0. If out of range, ArrayIndexOutOfBoundsException.

Example 2 — Array2D.java: Two-dimensional array

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();
        }
    }
}

Execution result

1 2 3 
4 5 6 

Memo: Access is in the order of row index → column index.

Example 3 — ArraysUtil.java: Sort·Copy·toString

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));
    }
}

Execution result

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

Note: to of copyOfRange(from, to) is exclusive.

Example 4 — IntVsInteger.java: primitive vs boxing

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

public class IntVsInteger {
    public static void main(String[] args) {
        int[] xs = new int[3];               //Default 0
        Integer[] ys = new Integer[3];        //default 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);
    }
}

Execution result

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

Note: Arrays.asList returns a fixed size List (except when calling .add).

Common Mistakes

  1. Call parentheses like nums.length() → length is a field
  2. ArrayIndexOutOfBoundsException out of index range
  3. Assume that the row lengths of the two-dimensional array are the same (can be jagged)
  4. Trap where Arrays.asList(int[]) becomes List<int[]> (IntStream is used in primitive array)
  5. Use == for array comparison (use Arrays.equals or Arrays.deepEquals)

Cleanup

  • Arrays are fast, fixed-size data structures.
  • Index is 0..length-1
  • Most utilities are gathered as static methods in the Arrays class.
  • If you need a mutable collection, List (next section)

Try it yourself

cd 03_collection_generic/11_array/src
javac ArraysUtil.java
java ArraysUtil

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

src/Array1D.javaJava
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);
    }
}
src/Array2D.javaJava
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();
        }
    }
}
src/ArraysUtil.javaJava
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));
    }
}
src/IntVsInteger.javaJava
import java.util.Arrays;
import java.util.List;

public class IntVsInteger {
    public static void main(String[] args) {
        int[] xs = new int[3];
        Integer[] ys = new Integer[3];
        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);
    }
}

Assignment

Problem 1 — Sum/maximum/average of arrays

  • File name: Homework01.java
  • Key concepts: enhanced for, cumulative

Requirements

  • Outputs the sum, maximum value, and average (2 decimal places) of the array {3, 7, 1, 9, 4}.

Expected output

sum=24
max=9
Average=4.80

Problem 2 — Matrix transpose

  • File name: Homework02.java
  • Core concepts: 2-dimensional array, index conversion

Requirements

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

Expected output

original
1 2 3 
4 5 6 
transposition
1 4 
2 5 
3 6 

Check the correct answer

After solving it yourself, compare it with the reference solution below.

Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

Homework01.javaJava
/** Sum, maximum value, average of array.*/
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 value=" + max);
        System.out.printf("average=%.2f%n", avg);
    }
}
Homework02.javaJava
/** 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("transposition");
        print(t);
    }

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

Learn this lesson with a mentor

Work through the Java + Spring Boot track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now