Java Arrays

A complete guide to arrays in Java: declaration and initialisation, element access, iteration, multi-dimensional and jagged arrays, passing arrays to methods, the java.util.Arrays utility class, arrays of objects, anonymous arrays, and System.arraycopy().

Array Declaration and Initialisation

An array in Java is a fixed-size, ordered collection of elements of the same type. Once you create an array with a given length, that length never changes. If you need a resizable sequence, you would use a class like ArrayList from the Collections framework instead. Arrays are the most fundamental data structure in the language, and every other collection type is built on top of them internally.

Three ways to declare and initialise an array

Java gives you three syntactic forms depending on whether you know the values upfront or only the size.

  • Declaration only:int[] scores;, declares a variable that can hold an int array, but does not allocate memory yet. The variable holds null until you assign an array to it.
  • Allocate by size:int[] scores = new int[5];, allocates an array of five integers. All elements are automatically initialised to their default value: 0 for numeric types, false for boolean, and null for reference types.
  • Array literal (initialiser list):int[] scores = {90, 85, 78, 92, 88};, allocates and fills the array in one step. The size is inferred from the number of values you provide.

Array Declaration and Initialisation

Java

All three forms of array creation, plus inspecting default values.

Accessing Array Elements

Array elements are accessed using a zero-based integer index inside square brackets. The first element is at index 0 and the last is at index length - 1. Attempting to read or write an index outside this range throws an ArrayIndexOutOfBoundsException at runtime, which is one of the most common bugs beginners encounter. There is no built-in bounds-check you can toggle off: Java always validates the index.

Reading and writing elements

Square-bracket notation works the same for both reading a value and assigning one.

  • arr[i] on the right side of = reads the element at index i.
  • arr[i] on the left side of = sets the element at index i to a new value.
  • The index expression can be any int-producing expression, not just a literal: arr[i + 1], arr[someMethod()] and so on are all valid.
  • Negative indices are not supported in Java. arr[-1] will always throw ArrayIndexOutOfBoundsException.

Accessing and Modifying Elements

Java

Reading, writing, and safely guard-checking array indices.

Array Length with .length

Every Java array has a public final field called length that stores the number of elements the array was created with. It is a field, not a method, so you write arr.length without parentheses. This is a frequent source of confusion because String uses a method length() with parentheses. The value stored in length is fixed at the time the array is created and cannot be changed.

Using .length

Java

Reading array length and using it to calculate the last valid index.

Iterating through Arrays

Java offers two main loop styles for walking over an array. The classic for loop gives you the index at each step, which you need whenever the position of an element matters. The enhanced for-each loop is cleaner when you only care about the values, not their positions.

Choosing the right loop

Both loops visit every element, but they give you different information.

  • Index-based for loop:for (int i = 0; i < arr.length; i++), use this when you need i, when you want to iterate in reverse, or when you need to modify elements in place.
  • Enhanced for-each loop:for (int val : arr), use this for a clean read-only traversal. You cannot modify the array element through the loop variable, and you do not have the index available.
  • while loop:Less idiomatic for arrays, but useful when the termination condition is more complex than a simple length check.

Iterating through an Array

Java

Index-based loop, for-each loop, and a reverse traversal.

Multi-dimensional Arrays (2D, 3D)

Java represents multi-dimensional arrays as arrays of arrays. A 2D array is an array where each element is itself a 1D array. This lets you model tabular data like a grid or matrix. You can extend the same concept to three or more dimensions, though arrays beyond 2D are uncommon in practice. Each dimension is accessed with its own pair of square brackets.

Declaring multi-dimensional arrays

Multi-dimensional arrays add one extra pair of brackets for each dimension.

  • 2D array by size:int[][] grid = new int[3][4];, creates a 3-row, 4-column grid. All 12 elements are initialised to 0.
  • 2D array literal:int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};, declares and fills a 3x3 matrix in one statement.
  • 3D array:int[][][] cube = new int[2][3][4];, allocates a 3-dimensional structure with 2 layers, 3 rows, and 4 columns.
  • Accessing elements:matrix[row][col] reads the element at the given row and column. Nested for loops are the standard way to iterate.

2D and 3D Arrays

Java

Creating, filling, and iterating a 2D matrix, then demonstrating a 3D array.

Jagged Arrays

Because Java implements multi-dimensional arrays as arrays of arrays, there is no requirement that each row has the same number of columns. An array where rows have different lengths is called a jagged array (or a ragged array). This is useful when you are modelling triangular data structures, such as Pascal's triangle, or when you want to avoid wasting memory on padding empty cells.

Jagged Arrays

Java

Allocating rows with different lengths and iterating safely using each row's own .length.

Arrays and Methods (Passing and Returning)

In Java, everything is passed by value. For arrays, the value that is passed is the reference: the memory address of the array object on the heap. This means that when you pass an array to a method and that method modifies elements, the changes are visible in the caller because both the caller and the method hold a reference to the same underlying array object. You can also return a newly created array from a method, giving the caller a fresh object.

Key behaviours when passing arrays

Understanding pass-by-reference-value prevents surprising bugs.

  • Modifying array elements inside a method affects the original array in the caller.
  • Reassigning the parameter variable (arr = new int[10]) inside the method does not affect the caller's variable: only the local copy of the reference is changed.
  • To avoid modifying the original, pass a copy using Arrays.copyOf() or System.arraycopy() before operating on it.
  • A method can return an array like any other type: just declare the return type as int[] or String[][] and use the return statement.

Arrays and Methods

Java

Passing an array to a method, modifying elements, and returning a new array.

The Arrays Class (java.util.Arrays)

The java.util.Arrays class is a utility class containing only static methods. It covers the most common array operations so you do not have to write them from scratch. The class handles all primitive types as well as object arrays. You need to add import java.util.Arrays; at the top of your file to use it.

Overview of key Arrays methods

Six methods cover the vast majority of everyday array utility needs.

  • Arrays.sort(arr):Sorts the array in ascending order in place, using a dual-pivot quicksort for primitives and a merge sort variant for objects. Fast and reliable for almost every use case.
  • Arrays.binarySearch(arr, key):Searches a sorted array for key and returns its index, or a negative number if not found. The array must be sorted before calling this.
  • Arrays.copyOf(original, newLength):Returns a new array with the first newLength elements of original. If newLength is greater than original.length, the extra positions are filled with default values.
  • Arrays.fill(arr, value):Sets every element of the array to value. Useful for resetting an array or initialising it to something other than the default zero.
  • Arrays.equals(a, b):Returns true if the two arrays have the same length and all corresponding elements are equal. The == operator on arrays checks reference equality, not content, so always use this method for content comparison.
  • Arrays.toString(arr):Returns a human-readable String representation like [1, 2, 3]. Invaluable for debugging. Without it, printing an array directly yields a cryptic reference like [I@5f4da5c3.

Arrays.sort() and Arrays.binarySearch()

Java

Sorting an array in place and then searching for a value with binary search.

Arrays.copyOf() and Arrays.fill()

Java

Creating a resized copy and filling an array with a constant value.

Arrays.equals() and Arrays.toString()

Java

Comparing array contents correctly and printing arrays in a readable format.

Array of Objects

Arrays are not limited to primitive types. You can create an array of any class, including your own. When you allocate an object array with new, each slot is initialised to null, not to any object. You must explicitly assign an object to each index before reading from it, otherwise you will encounter a NullPointerException.

Array of Objects

Java

Creating an array of custom objects, populating it, and iterating over the results.

Anonymous Arrays

An anonymous array is an array that is created and used immediately without being assigned to a named variable. The syntax combines new int[] with an initialiser list. This is handy when you need to pass a one-off array directly to a method call or as a return value without the clutter of declaring a separate variable.

Anonymous Arrays

Java

Passing an array literal directly to a method without declaring a named variable.

System.arraycopy()

System.arraycopy() is a native method that copies a range of elements from one array to another. It is the most performant way to copy array data in Java because the JVM implements it at the native level, avoiding the overhead of a Java for loop. The signature is:

System.arraycopy() parameters

System.arraycopy(src, srcPos, dest, destPos, length)

  • src:The source array to copy from.
  • srcPos:The starting index in the source array.
  • dest:The destination array to copy into.
  • destPos:The starting index in the destination array.
  • length:The number of elements to copy.

System.arraycopy() vs Arrays.copyOf()

Both copy array data, but they serve slightly different purposes.

  • System.arraycopy() copies into an existing destination array and gives you full control over source and destination positions. It does not allocate a new array for you.
  • Arrays.copyOf() always allocates and returns a brand-new array. It is more convenient when you want a resized copy but do not need control over the destination offset.
  • System.arraycopy() is generally faster for large data volumes because it is a single native call.

System.arraycopy()

Java

Copying a full array, copying a slice, and overlapping within the same array.

Quiz - Test Your Knowledge

Ten questions covering array declaration, indexing, iteration, multi-dimensional and jagged arrays, the Arrays utility class, and System.arraycopy(). Read each option carefully before selecting your answer.

Knowledge Check

1. What is the index of the last element in an array declared as int[] arr = new int[10]?

2. Which property gives you the number of elements in a Java array?

3. What exception is thrown when you access an array index that is out of bounds?

4. Which statement correctly declares and initialises a 3x4 two-dimensional array of integers?

5. What does Arrays.binarySearch() require before it can be called correctly?

6. What does Arrays.copyOf(original, 3) return when original = {10, 20, 30, 40, 50}?

7. What distinguishes a jagged array from a regular 2D array in Java?

8. Which Arrays utility method converts an array to a human-readable String like "[1, 2, 3]"?

9. When you pass an array to a method in Java, what is actually passed?

10. Which method efficiently copies a range of elements from one array to another at the system level?