Skip to content

Module 3 · Control Flow and Arrays — topic 4 of 4

Arrays

Creating, filling and iterating over arrays, default values, multi-dimensional and jagged arrays, the Arrays utility class, and arrays as method parameters.

Beginner 18 min read·Lesson 12 of 39 in Java Programming

Learning objectives

  • Declare, create and initialise one- and two-dimensional arrays
  • Use java.util.Arrays to print, sort, search, fill and copy arrays
  • Explain why arrays passed to methods can be modified

Definition

An array is a fixed-length object that stores elements of one type in contiguous, indexed slots from 0 to length − 1. Array variables are references to array objects on the heap.

Introduction

An array stores many values of the same type under one name: the marks of a class, the days in each month, the pixels of an image. Java arrays know their own length and check every index, so reading past the end throws an exception instead of silently corrupting memory as it can in C.

Why it matters

Arrays are the foundation of data structures and algorithms — searching, sorting, dynamic programming — and of classes such as ArrayList.

Many interview questions are array problems: two pointers, prefix sums, sliding windows.

Detailed explanation

Creating arrays. int[] marks = new int[5]; creates five ints set to 0. int[] primes = {2, 3, 5, 7}; creates and fills one in a single step. The length is fixed when the array is created and is available as marks.length (a field, not a method).

Default values. New arrays are filled with 0, 0.0, false, '\u0000' or null depending on the element type, so an array of objects starts as a row of nulls.

Access. marks[0] is the first element and marks[marks.length - 1] the last. An invalid index throws ArrayIndexOutOfBoundsException.

Reference semantics. An array variable holds a reference. Assigning it (int[] b = a;) or passing it to a method shares the same array, so a method can modify its elements. To copy, use Arrays.copyOf(a, a.length) or a.clone().

Multi-dimensional arrays are arrays of arrays: int[][] grid = new int[3][4];. Rows may have different lengths (*jagged* arrays): int[][] tri = new int[4][]; tri[i] = new int[i + 1];.

java.util.Arrays provides toString and deepToString for printing, sort, binarySearch (on sorted arrays), fill, copyOf, copyOfRange, equals and stream.

When you need a sequence that grows and shrinks, use ArrayList (module 8) instead of an array.

Syntax

Java
int[] a = new int[5]; // [0, 0, 0, 0, 0]
String[] names = {"Asha", "Ravi"};
int last = a[a.length - 1];
int[][] grid = new int[3][4]; // 3 rows, 4 columns
int[] copy = Arrays.copyOf(a, a.length);
Arrays.sort(a);
System.out.println(Arrays.toString(a));
  • length has no parentheses for arrays (but strings use length()).
  • Printing an array directly shows something like [I@1b6d3586; use Arrays.toString.
  • Arrays.binarySearch requires a sorted array.

Code examples

Creating and iterating

Java
import java.util.Arrays;
public class Basics {
public static void main(String[] args) {
int[] marks = {72, 95, 58, 81, 66};
int max = marks[0], min = marks[0], sum = 0;
for (int m : marks) {
sum += m;
if (m > max) max = m;
if (m < min) min = m;
}
System.out.println(Arrays.toString(marks));
System.out.println("length " + marks.length + ", sum " + sum + ", max " + max + ", min " + min);
double[] d = new double[3];
String[] s = new String[2];
System.out.println(Arrays.toString(d) + " " + Arrays.toString(s));
}
}
Output
[72, 95, 58, 81, 66]
length 5, sum 372, max 95, min 58
[0.0, 0.0, 0.0] [null, null]

Arrays are shared by reference

Java
import java.util.Arrays;
public class Shared {
static void addBonus(int[] marks, int bonus) {
for (int i = 0; i < marks.length; i++) marks[i] += bonus;
}
public static void main(String[] args) {
int[] marks = {70, 80};
int[] copy = marks.clone();
addBonus(marks, 5);
System.out.println(Arrays.toString(marks) + " " + Arrays.toString(copy));
}
}
Output
[75, 85] [70, 80]

More examples

Arrays utilities and a 2D table

Java
import java.util.Arrays;
public class Tools {
public static void main(String[] args) {
int[] data = {42, 7, 19, 73, 7, 25};
int[] sorted = Arrays.copyOf(data, data.length);
Arrays.sort(sorted);
System.out.println("sorted: " + Arrays.toString(sorted));
System.out.println("index of 25: " + Arrays.binarySearch(sorted, 25));
System.out.println("original unchanged: " + Arrays.toString(data));
System.out.println("middle part: " + Arrays.toString(Arrays.copyOfRange(sorted, 2, 4)));
int[][] sales = {{120, 90, 150}, {80, 110, 95}};
String[] shops = {"North", "South"};
for (int r = 0; r < sales.length; r++) {
int total = 0;
for (int v : sales[r]) total += v;
System.out.println(shops[r] + " " + Arrays.toString(sales[r]) + " total " + total);
}
int[][] triangle = new int[4][];
for (int i = 0; i < triangle.length; i++) {
triangle[i] = new int[i + 1];
triangle[i][0] = triangle[i][i] = 1;
for (int j = 1; j < i; j++) triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
}
System.out.println(Arrays.deepToString(triangle));
}
}
Output
sorted: [7, 7, 19, 25, 42, 73]
index of 25: 3
original unchanged: [42, 7, 19, 73, 7, 25]
middle part: [19, 25]
North [120, 90, 150] total 360
South [80, 110, 95] total 285
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]]

Step-by-step explanation

  • Arrays.copyOf makes an independent copy so sorting it leaves data untouched.
  • Arrays.binarySearch finds 25 at index 3 of the sorted copy; on an unsorted array its result would be meaningless.
  • copyOfRange(sorted, 2, 4) copies indexes 2 and 3 (the end index is exclusive).
  • sales is a 2D array: sales[r] is a whole row, which a for-each loop can total.
  • triangle is jagged: row i has i + 1 elements, filled with Pascal's rule, and deepToString prints nested arrays.

Expected output

Running “Arrays utilities and a 2D table” prints exactly:

TextOutput
sorted: [7, 7, 19, 25, 42, 73]
index of 25: 3
original unchanged: [42, 7, 19, 73, 7, 25]
middle part: [19, 25]
North [120, 90, 150] total 360
South [80, 110, 95] total 285
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]]

Practical applications

  • Storing fixed-size data such as days per month or a game board
  • Buffers for reading files and network data (byte[])
  • Matrices for graphics and scientific computing
  • Lookup tables that replace long if/else chains

Best practices

  • Use for-each to read elements and an index loop to modify them.
  • Use Arrays.toString and deepToString when debugging.
  • Prefer ArrayList when the number of elements changes.

Common mistakes

Printing an array directly

Avoid

System.out.println(marks); // [I@6d06d69c

Prefer

System.out.println(Arrays.toString(marks));

Arrays don't override toString, so printing one shows its type code and hash, not its elements.

Thinking assignment copies an array

Avoid

int[] backup = marks;
marks[0] = 0; // backup[0] is now 0 too

Prefer

int[] backup = marks.clone();
marks[0] = 0; // backup unchanged

Assignment copies the reference, so both names refer to the same array.

Important notes

  • Arrays.equals(a, b) compares contents; a.equals(b) and a == b compare references.
  • Arrays.sort on primitives uses a dual-pivot quicksort; on objects it uses a stable merge sort (TimSort).

Key takeaways

  • Arrays have a fixed length, zero-based indexes and default values.
  • Array variables are references: assignment and parameters share the array.
  • java.util.Arrays prints, sorts, searches and copies arrays.

Try it yourself

  1. 1
    Reverse an array in place using two indexes that move towards each other.
  2. 2
    Find the second-largest value in an array in one pass.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

8 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
  • BeginnerWhat happens when this runs? `int[] a = {1, 2, 3}; System.out.println(a[3]);`
Practise this topic