Arrays
Create, loop over, copy, sort and search arrays, plus 2D arrays and the Arrays helper class.
Imagine storing the marks of 40 students in 40 separate variables. An array solves this: one variable holding a fixed number of values of the same type, each accessed by a numeric index.
Creating arrays#
Key facts:
- The type is written
int[]("array of int"). Java also acceptsint scores[], butint[] scoresis the standard style. - The length is fixed when the array is created. Need it to grow? Use
ArrayList(see the Lists lesson). - New arrays are filled with default values:
0for numbers,falseforboolean,'\u0000'forcharandnullfor objects such asString.
Reading and writing elements#
Indexes start at 0, so the last index is length - 1:
Note that length is a field, not a method: scores.length, without parentheses (unlike String's length()).
Accessing an index outside 0..length-1 crashes at runtime:
Looping over arrays#
Use a classic for when you need the index, and the enhanced for when you just need each value:
Sum, average, minimum, maximum and "count how many match" are the bread-and-butter array algorithms. Practise writing them by hand.
Arrays are reference types#
An array variable holds a reference to the array object. Assigning it to another variable copies the reference, not the elements:
The Arrays helper class#
java.util.Arrays has ready-made methods for common jobs:
Arrays.stream(...) opens the door to the Streams API, which you will learn in the advanced module.
Arrays and methods#
Arrays can be passed to and returned from methods:
Because the method receives a copy of the reference, doubleInPlace modifies the caller's array. Returning a new array, as reversed does, is usually safer and easier to reason about.
Two-dimensional arrays#
A 2D array is an array of arrays, perfect for grids, tables and game boards:
Read grid[r][c] as "row r, column c". Use Arrays.deepToString to print nested arrays.
Classic algorithm: linear search#
Linear search checks every element, so it takes time proportional to the array length. On a sorted array, Arrays.binarySearch halves the search space on every step and is dramatically faster for big arrays.
Arrays vs ArrayList#
In day-to-day application code, Lists are more common. Arrays still matter for performance-critical code, main(String[] args), varargs, and interviews.
Common mistakes#
ArrayIndexOutOfBoundsExceptionfrom using<=instead of<in the loop condition.- Printing an array directly (
[I@1b6d3586) instead of usingArrays.toString. - Comparing arrays with
==instead ofArrays.equals. - Thinking
b = acopies the array. - Calling
Arrays.binarySearchon an unsorted array: the result is undefined.
What's next#
You can now store and process collections of values. Next we explore the most used type in Java, String, and its fast, mutable partner StringBuilder.
Check your understanding
Quick quiz
1.What is the last valid index of
int[] a = new int[5];?2.What does
System.out.println(new int[]{1, 2, 3});print?3.After
int[] a = {1, 2, 3}; int[] b = a; b[0] = 9;, what isa[0]?
Finished reading?
Mark this lesson complete to track your progress.