Skip to main content

Lesson 4 of 10

Arrays Utility Class

java.util.Arrays provides static utility methods for sorting, searching, filling, copying, and comparing arrays. Combined with Java's built-in sort and binary search algorithms, it covers the most common array operations without writing them from scratch.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Arrays - Sort, Search, Copy, Fill

Arrays - Sort, Search, Copy, Fill
import java.util.Arrays;
import java.util.Comparator;

public class ArraysUtility {
    public static void main(String[] args) {
        // Sort primitives (in-place, ascending)
        int[] scores = {88, 72, 95, 60, 88};
        Arrays.sort(scores);                           // {60, 72, 88, 88, 95}
        System.out.println(Arrays.toString(scores));   // [60, 72, 88, 88, 95]

        // Binary search (array MUST be sorted first)
        int idx = Arrays.binarySearch(scores, 88);     // 2 or 3 (any matching index)
        System.out.println("Found 88 at index: " + idx);

        // Sort objects - natural order
        String[] names = {"Charlie", "Alice", "Bob"};
        Arrays.sort(names);                            // ["Alice", "Bob", "Charlie"]
        System.out.println(Arrays.toString(names));

        // Sort with Comparator - reverse order
        Arrays.sort(names, Comparator.reverseOrder()); // ["Charlie", "Bob", "Alice"]

        // 2D sort - sort by first column
        int[][] matrix = {{3, 1}, {1, 4}, {2, 2}};
        Arrays.sort(matrix, (a, b) -> a[0] - b[0]);  // sort by column 0
        System.out.println(Arrays.deepToString(matrix)); // [[1, 4], [2, 2], [3, 1]]

        // Copy
        int[] original = {1, 2, 3, 4, 5};
        int[] full  = Arrays.copyOf(original, original.length);       // full copy
        int[] partial = Arrays.copyOfRange(original, 1, 4);           // {2, 3, 4}
        System.out.println(Arrays.toString(partial));

        // Fill - set all elements to a value
        int[] empty = new int[5];
        Arrays.fill(empty, 99);                        // {99, 99, 99, 99, 99}

        // Equality
        int[] a = {1, 2, 3};
        int[] b = {1, 2, 3};
        System.out.println(a == b);               // false (different references)
        System.out.println(Arrays.equals(a, b));  // true  (element comparison)

        // Parallel sort (useful for large arrays - uses Fork/Join)
        int[] large = new Random().ints(1_000_000).toArray();
        Arrays.parallelSort(large);  // faster than sort() for 100k+ elements
    }
}
Diagram
Loading diagram…

Visual architecture and concepts for Arrays Utility Class

Quick Quiz

Topics in This Module

0/10 done