Codectionary / Developer documentation / Java

Arrays Utility Class

java.util.Arrays is a utility class providing static helper methods specifically for working with arrays - sorting, searching, filling, comparing, copying, and converting to a readable String or a List. Since arrays don't have built-in methods of their own the way ArrayList does, this utility class fills that gap for common array tasks.

Syntax

Arrays.methodName(array);

Examples

Sorting and Printing Arrays

Sorting an array and converting it to a readable string.

import java.util.Arrays;

int[] numbers = {5, 2, 8, 1, 9};

Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));  // [1, 2, 5, 8, 9]

int[][] matrix = {{1, 2}, {3, 4}};
System.out.println(Arrays.deepToString(matrix));  // [[1, 2], [3, 4]]

Searching and Filling

Binary search on a sorted array, and filling an array with a value.

import java.util.Arrays;

int[] sorted = {1, 3, 5, 7, 9};
int index = Arrays.binarySearch(sorted, 7);
System.out.println(index);  // 3

int[] scores = new int[5];
Arrays.fill(scores, 100);
System.out.println(Arrays.toString(scores));  // [100, 100, 100, 100, 100]

Copying Arrays

Creating independent copies, whole or partial, of an array.

import java.util.Arrays;

int[] original = {1, 2, 3, 4, 5};

int[] fullCopy = Arrays.copyOf(original, original.length);
int[] extended = Arrays.copyOf(original, 8);       // pads with 0s
int[] partial = Arrays.copyOfRange(original, 1, 4); // indices 1 to 3

System.out.println(Arrays.toString(extended));  // [1, 2, 3, 4, 5, 0, 0, 0]
System.out.println(Arrays.toString(partial));    // [2, 3, 4]

Converting Between Array and List

Arrays.asList() provides a quick bridge between an array and the List interface.

import java.util.Arrays;
import java.util.List;

String[] namesArray = {"John", "Zain", "Jamal"};
List<String> namesList = Arrays.asList(namesArray);

System.out.println(namesList);  // [John, Zain, Jamal]

// Note: Arrays.asList() returns a FIXED-SIZE list backed by the array
// namesList.add("New");  // would throw UnsupportedOperationException

Best practices

  • Use Arrays.toString() or Arrays.deepToString() (for multi-dimensional arrays) to print array contents - printing an array directly shows only its memory reference
  • Remember Arrays.asList() returns a fixed-size list backed by the original array - wrap it in new ArrayList<>(...) if you need a fully resizable list
  • Use Arrays.sort() before Arrays.binarySearch() - binary search requires the array to already be sorted to work correctly
  • Use Arrays.equals() to compare array contents - == and .equals() on arrays only compare references, not element values

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading