Arrays
Create, index and sort fixed-size arrays, and know when to reach for a List instead.
Open this lesson in the learning hubKey points
- An array is a fixed-size block of one type. The size is set at creation and
lengthis a field, not a method. - Indexes start at 0. Reading past the end throws
ArrayIndexOutOfBoundsException. - New arrays come pre-filled:
0for numbers,falsefor booleans,nullfor object types. Arrays.toString()prints,Arrays.sort()sorts in place,Arrays.copyOf()resizes into a new array.- A 2D array is an array of arrays, so rows may differ in length. Print it with
Arrays.deepToString(). - Printing an array directly gives something like
[I@1b6d— that is the defaulttoString, not the contents.
Example
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] nums = {5, 3, 9, 1};
System.out.println("length: " + nums.length + ", first: " + nums[0]);
Arrays.sort(nums);
System.out.println("sorted: " + Arrays.toString(nums));
System.out.println("binarySearch(9): index " + Arrays.binarySearch(nums, 9));
int[] bigger = Arrays.copyOf(nums, 6);
System.out.println("copyOf pads with 0: " + Arrays.toString(bigger));
String[] blanks = new String[3];
System.out.println("object arrays start null: " + Arrays.toString(blanks));
int[][] grid = {{1, 2}, {3, 4, 5}};
System.out.println("jagged grid: " + Arrays.deepToString(grid) + ", row 1 length " + grid[1].length);
try {
System.out.println(nums[9]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("out of bounds -> " + e.getMessage());
}
}
}
Arrays are fixed-size and fast; use a List when the size has to change.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.