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.
1. Sorting, Searching and Printing
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));
}
}
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]]
sortuses Dual-Pivot Quicksort for primitives and a stable merge sort (TimSort) for objects; pass aComparatorfor custom orders.- Natural
Stringorder is case-sensitive: uppercase letters come before lowercase. binarySearchrequires a sorted array. If the key is missing it returns-(insertionPoint) - 1.toStringprints one-dimensional arrays; usedeepToStringfor nested arrays. Printing an array directly gives something like[I@1b6d3586.parallelSortcan speed up sorting very large arrays on multi-core machines.
2. Filling, Copying and Comparing
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));
}
}
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]
copyOftruncates or pads (with 0, false or null);copyOfRangecopies[from, to).- Pitfall:
array.equals(other)is inherited fromObjectand compares references. UseArrays.equals(ordeepEqualsfor nested arrays) andArrays.hashCode. compare(Java 9) compares lexicographically;mismatchreturns the first differing index, or −1.setAllcomputes each element from its index.
3. asList and Streams
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));
}
}
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.asListreturns a fixed-size list backed by the array:setwrites through, butaddandremovethrow. Wrap it innew ArrayList<>(...)for a growable list, or useList.offor an immutable one.Arrays.asList(intArray)does not give aList<Integer>; it gives aList<int[]>with one element. UseArrays.stream(ints).boxed().toList().Arrays.streambrings 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
| Method | Purpose |
|---|---|
sort, parallelSort | Sort whole array or a range, optionally with a Comparator |
binarySearch | Find a key in a sorted array |
toString, deepToString | Readable text |
fill, setAll | Assign values |
copyOf, copyOfRange | Create resized or partial copies |
equals, deepEquals, hashCode, compare, mismatch | Content comparison |
asList | Fixed-size list view |
stream | Stream of the elements |
5. Summary
Arraysprovides static helpers for every common array task.- Sort with
sort, search sorted arrays withbinarySearch, print withtoString/deepToString. - Compare contents with
Arrays.equals, never with==orarray.equals. asListis a fixed-size view; copy it into anArrayListto grow it.
Related Tutorials
Frequently Asked Questions (FAQ)
Q1. Which algorithm does Arrays.sort use?
Dual-Pivot Quicksort for primitive arrays and TimSort (a stable merge sort) for object arrays.
Q2. Why does binarySearch return a negative number?
The key was not found. The value is -(insertion point) - 1, where the insertion point is where the key would go.
Q3. Why can't I add to a list from Arrays.asList?
It is a fixed-size view of the array. Create new ArrayList<>(Arrays.asList(arr)) to get a resizable list.
Q4. What is the difference between Arrays.asList and List.of?
asList is a fixed-size, writable view backed by the array and allows nulls. List.of is fully immutable and rejects nulls.
Q5. How do I copy an array?
Arrays.copyOf(arr, arr.length), arr.clone() or System.arraycopy. All make shallow copies.
Q6. Is Arrays.sort stable?
For object arrays yes; equal elements keep their relative order. Stability does not matter for primitives.