00:00

Arrays Class in Java – Sorting, Searching, Copying and More

java.util.Arrays is a utility class of static methods for working with arrays: sorting, searching, printing, filling, copying, comparing, and converting arrays to lists and streams. Arrays themselves have almost no useful methods, so Arrays is the toolbox you reach for whenever you work with them.

This tutorial covers the most important methods with runnable examples, and explains the pitfalls of equals on arrays and of Arrays.asList.

SortSearchPrint.java
import java.util.Arrays;
import java.util.Comparator;

public class SortSearchPrint {
    public static void main(String[] args) {
        int[] nums = {42, 7, 19, 3, 25};
        System.out.println("original       : " + Arrays.toString(nums));
        Arrays.sort(nums);
        System.out.println("sort           : " + Arrays.toString(nums));
        System.out.println("binarySearch 19: index " + Arrays.binarySearch(nums, 19));
        System.out.println("binarySearch 20: " + Arrays.binarySearch(nums, 20) + " (negative: not found)");

        String[] names = {"Ravi", "asha", "Meera", "kiran"};
        Arrays.sort(names);
        System.out.println("natural order  : " + Arrays.toString(names));
        Arrays.sort(names, String.CASE_INSENSITIVE_ORDER);
        System.out.println("ignore case    : " + Arrays.toString(names));
        Arrays.sort(names, Comparator.comparing(String::length).reversed());
        System.out.println("by length desc : " + Arrays.toString(names));

        int[] part = {9, 8, 7, 6, 5, 4};
        Arrays.sort(part, 1, 4);                       // sort only indexes 1..3
        System.out.println("range sort     : " + Arrays.toString(part));

        int[][] grid = {{1, 2}, {3, 4}};
        System.out.println("deepToString   : " + Arrays.deepToString(grid));
    }
}
Output
original       : [42, 7, 19, 3, 25]
sort           : [3, 7, 19, 25, 42]
binarySearch 19: index 2
binarySearch 20: -4 (negative: not found)
natural order  : [Meera, Ravi, asha, kiran]
ignore case    : [asha, kiran, Meera, Ravi]
by length desc : [kiran, Meera, asha, Ravi]
range sort     : [9, 6, 7, 8, 5, 4]
deepToString   : [[1, 2], [3, 4]]
  • sort uses Dual-Pivot Quicksort for primitives and a stable merge sort (TimSort) for objects; pass a Comparator for custom orders.
  • Natural String order is case-sensitive: uppercase letters come before lowercase.
  • binarySearch requires a sorted array. If the key is missing it returns -(insertionPoint) - 1.
  • toString prints one-dimensional arrays; use deepToString for nested arrays. Printing an array directly gives something like [I@1b6d3586.
  • parallelSort can speed up sorting very large arrays on multi-core machines.

2. Filling, Copying and Comparing

FillCopyCompare.java
import java.util.Arrays;

public class FillCopyCompare {
    public static void main(String[] args) {
        int[] seats = new int[6];
        Arrays.fill(seats, -1);                               // fill all
        Arrays.fill(seats, 2, 4, 0);                          // fill a range
        System.out.println("fill          : " + Arrays.toString(seats));

        int[] src = {1, 2, 3, 4, 5};
        int[] bigger = Arrays.copyOf(src, 8);                 // pads with zeros
        int[] middle = Arrays.copyOfRange(src, 1, 4);
        System.out.println("copyOf(8)     : " + Arrays.toString(bigger));
        System.out.println("copyOfRange   : " + Arrays.toString(middle));

        int[] a = {1, 2, 3}, b = {1, 2, 3};
        System.out.println("a == b        : " + (a == b));
        System.out.println("a.equals(b)   : " + a.equals(b));          // identity, like ==
        System.out.println("Arrays.equals : " + Arrays.equals(a, b));  // content
        System.out.println("hashCode same : " + (Arrays.hashCode(a) == Arrays.hashCode(b)));
        System.out.println("compare       : " + Arrays.compare(new int[]{1, 2}, new int[]{1, 3}));
        System.out.println("mismatch      : " + Arrays.mismatch(new int[]{1, 2, 3}, new int[]{1, 9, 3}));

        int[] squares = new int[5];
        Arrays.setAll(squares, i -> i * i);
        System.out.println("setAll        : " + Arrays.toString(squares));
    }
}
Output
fill          : [-1, -1, 0, 0, -1, -1]
copyOf(8)     : [1, 2, 3, 4, 5, 0, 0, 0]
copyOfRange   : [2, 3, 4]
a == b        : false
a.equals(b)   : false
Arrays.equals : true
hashCode same : true
compare       : -1
mismatch      : 1
setAll        : [0, 1, 4, 9, 16]
  • copyOf truncates or pads (with 0, false or null); copyOfRange copies [from, to).
  • Pitfall: array.equals(other) is inherited from Object and compares references. Use Arrays.equals (or deepEquals for nested arrays) and Arrays.hashCode.
  • compare (Java 9) compares lexicographically; mismatch returns the first differing index, or −1.
  • setAll computes each element from its index.

3. asList and Streams

AsListAndStreams.java
import java.util.*;

public class AsListAndStreams {
    public static void main(String[] args) {
        String[] arr = {"java", "spring", "kafka"};
        List<String> view = Arrays.asList(arr);           // fixed-size list BACKED by the array
        view.set(0, "JAVA");
        System.out.println("array changed via list: " + arr[0]);
        try {
            view.add("docker");
        } catch (UnsupportedOperationException e) {
            System.out.println("asList add(): UnsupportedOperationException (fixed size)");
        }
        List<String> growable = new ArrayList<>(Arrays.asList(arr));
        growable.add("docker");
        System.out.println("ArrayList copy: " + growable);

        int[] marks = {72, 88, 95, 61};
        System.out.println("stream sum    : " + Arrays.stream(marks).sum());
        System.out.println("stream average: " + Arrays.stream(marks).average().orElse(0));
        System.out.println("above 80      : " + Arrays.toString(Arrays.stream(marks).filter(m -> m > 80).toArray()));

        Integer[] boxed = {5, 1, 4};
        Arrays.sort(boxed, Collections.reverseOrder());
        System.out.println("reverse sort  : " + Arrays.toString(boxed));
    }
}
Output
array changed via list: JAVA
asList add(): UnsupportedOperationException (fixed size)
ArrayList copy: [JAVA, spring, kafka, docker]
stream sum    : 316
stream average: 79.0
above 80      : [88, 95]
reverse sort  : [5, 4, 1]
  • Arrays.asList returns a fixed-size list backed by the array: set writes through, but add and remove throw. Wrap it in new ArrayList<>(...) for a growable list, or use List.of for an immutable one.
  • Arrays.asList(intArray) does not give a List<Integer>; it gives a List<int[]> with one element. Use Arrays.stream(ints).boxed().toList().
  • Arrays.stream brings the full Stream API (sum, average, filter, map) to arrays.
  • Descending sort with a comparator works only for object arrays such as Integer[].

4. Method Reference

MethodPurpose
sort, parallelSortSort whole array or a range, optionally with a Comparator
binarySearchFind a key in a sorted array
toString, deepToStringReadable text
fill, setAllAssign values
copyOf, copyOfRangeCreate resized or partial copies
equals, deepEquals, hashCode, compare, mismatchContent comparison
asListFixed-size list view
streamStream of the elements

5. Summary

  • Arrays provides static helpers for every common array task.
  • Sort with sort, search sorted arrays with binarySearch, print with toString/deepToString.
  • Compare contents with Arrays.equals, never with == or array.equals.
  • asList is a fixed-size view; copy it into an ArrayList to grow it.

Related Tutorials