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.
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
lengthhas no parentheses for arrays (but strings uselength()).- Printing an array directly shows something like
[I@1b6d3586; use Arrays.toString. - Arrays.binarySearch requires a sorted array.
Code examples
Creating and iterating
[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
[75, 85] [70, 80]
More examples
Arrays utilities and a 2D table
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.copyOfmakes an independent copy so sorting it leavesdatauntouched.Arrays.binarySearchfinds 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).salesis a 2D array:sales[r]is a whole row, which a for-each loop can total.triangleis jagged: row i has i + 1 elements, filled with Pascal's rule, anddeepToStringprints nested arrays.
Expected output
Running “Arrays utilities and a 2D table” prints exactly:
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
Prefer
Arrays don't override toString, so printing one shows its type code and hash, not its elements.
Thinking assignment copies an array
Avoid
Prefer
Assignment copies the reference, so both names refer to the same array.
Important notes
Arrays.equals(a, b)compares contents;a.equals(b)anda == bcompare references.Arrays.sorton 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
- 1Reverse an array in place using two indexes that move towards each other.
- 2Find 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]);`