Arrays Utility Class
The java.util.Arrays class is a toolbox full of ready-made methods for the most common array tasks — sorting, searching, copying, comparing, and filling. Instead of writing those algorithms yourself, you just call the right static method and move on.
Importing Arrays
All methods live in java.util.Arrays, so add this import at the top of your file:
import java.util.Arrays;
Every method is static, meaning you call them on the class itself: Arrays.sort(...), Arrays.fill(...), etc.
Sorting — Arrays.sort()
Arrays.sort() sorts an array in place (it modifies the original). For primitive arrays it uses a tuned dual-pivot Quicksort; for object arrays it uses TimSort (a stable merge sort).
int[] numbers = {5, 2, 8, 1, 9, 3};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
Output:
[1, 2, 3, 5, 8, 9]
You can also sort just a portion of the array by providing fromIndex (inclusive) and toIndex (exclusive):
int[] data = {7, 3, 5, 1, 9, 4};
Arrays.sort(data, 1, 4); // sorts indices 1, 2, 3 only
System.out.println(Arrays.toString(data));
Output:
[7, 1, 3, 5, 9, 4]
Sorting works with any Comparable object type, like String:
String[] fruits = {"Mango", "Apple", "Cherry", "Banana"};
Arrays.sort(fruits);
System.out.println(Arrays.toString(fruits));
Output:
[Apple, Banana, Cherry, Mango]
Tip: To sort in reverse order, pass a
Comparator. You cannot useComparator.reverseOrder()with primitive arrays — you need a boxed type likeInteger[].
Integer[] nums = {5, 2, 8, 1};
Arrays.sort(nums, Comparator.reverseOrder());
System.out.println(Arrays.toString(nums));
Output:
[8, 5, 2, 1]
Searching — Arrays.binarySearch()
Arrays.binarySearch() finds the index of a value in a sorted array using binary search (O(log n) time).
int[] sorted = {1, 3, 5, 7, 9, 11};
int idx = Arrays.binarySearch(sorted, 7);
System.out.println("Found at index: " + idx);
Output:
Found at index: 3
Warning: The array must be sorted before calling
binarySearch(). Searching an unsorted array produces undefined results — the method won’t tell you it’s unsorted.
If the value is not found, the method returns a negative insertion point: -(insertion point) - 1. You can use this to figure out where the value would go:
int[] sorted = {1, 3, 5, 7, 9};
int result = Arrays.binarySearch(sorted, 6);
// result = -4 → would be inserted at index 3
System.out.println(result); // -4
Filling — Arrays.fill()
Arrays.fill() sets every element (or a range) to the same value — handy for initializing arrays:
int[] grid = new int[6];
Arrays.fill(grid, 42);
System.out.println(Arrays.toString(grid));
Output:
[42, 42, 42, 42, 42, 42]
Range version:
int[] grid = new int[6];
Arrays.fill(grid, 2, 5, 99); // indices 2, 3, 4
System.out.println(Arrays.toString(grid));
Output:
[0, 0, 99, 99, 99, 0]
Copying — Arrays.copyOf() and Arrays.copyOfRange()
Arrays.copyOf() creates a new array of the specified length, copying as many elements as fit. If the new length is longer, the extra slots are filled with default values (0, false, null).
int[] original = {10, 20, 30, 40, 50};
int[] shorter = Arrays.copyOf(original, 3);
int[] longer = Arrays.copyOf(original, 7);
System.out.println(Arrays.toString(shorter));
System.out.println(Arrays.toString(longer));
Output:
[10, 20, 30]
[10, 20, 30, 40, 50, 0, 0]
Arrays.copyOfRange() lets you copy a specific slice:
int[] original = {10, 20, 30, 40, 50};
int[] slice = Arrays.copyOfRange(original, 1, 4); // indices 1, 2, 3
System.out.println(Arrays.toString(slice));
Output:
[20, 30, 40]
Note: Both methods return a brand-new array — the original is never modified. This is different from
Arrays.sort(), which modifies in place.
Comparing — Arrays.equals() and Arrays.deepEquals()
The == operator checks if two array variables point to the same object, not if their contents match. Use Arrays.equals() for a proper element-by-element comparison:
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
System.out.println(a == b); // false (different objects)
System.out.println(Arrays.equals(a, b)); // true (same contents)
For multidimensional arrays, use Arrays.deepEquals():
int[][] matrix1 = {{1, 2}, {3, 4}};
int[][] matrix2 = {{1, 2}, {3, 4}};
System.out.println(Arrays.equals(matrix1, matrix2)); // false!
System.out.println(Arrays.deepEquals(matrix1, matrix2)); // true
Warning:
Arrays.equals()on a 2D array only compares the outer array’s references, not the nested contents. Always usedeepEquals()for nested arrays.
Converting to String — Arrays.toString() and Arrays.deepToString()
These are incredibly useful for debugging. Arrays.toString() gives you a human-readable representation:
double[] prices = {9.99, 14.50, 3.75};
System.out.println(Arrays.toString(prices));
Output:
[9.99, 14.5, 3.75]
For multidimensional arrays, use Arrays.deepToString():
int[][] matrix = {{1, 2, 3}, {4, 5, 6}};
System.out.println(Arrays.deepToString(matrix));
Output:
[[1, 2, 3], [4, 5, 6]]
Converting to a List — Arrays.asList()
Arrays.asList() wraps an array in a fixed-size List. This is useful for passing an array to methods that expect a List.
String[] colors = {"Red", "Green", "Blue"};
List<String> colorList = Arrays.asList(colors);
System.out.println(colorList);
Output:
[Red, Green, Blue]
Warning: The returned list is fixed-size — you can update existing elements, but calling
add()orremove()throws anUnsupportedOperationException. To get a fully mutable list, wrap it:new ArrayList<>(Arrays.asList(...)).
Parallel Sorting — Arrays.parallelSort()
Introduced in Java 8, Arrays.parallelSort() splits the array, sorts segments concurrently using the Fork/Join pool, then merges. For large arrays this is significantly faster on multi-core hardware:
int[] bigArray = new int[1_000_000];
// ... fill with values ...
Arrays.parallelSort(bigArray);
For small arrays the overhead of thread coordination isn’t worth it — Arrays.sort() is fine. The JDK’s own threshold for switching to parallel is typically 8192 elements.
Quick Reference Table
| Method | What it does | Modifies original? |
|---|---|---|
Arrays.sort(arr) | Sorts ascending in place | Yes |
Arrays.sort(arr, from, to) | Sorts a sub-range | Yes |
Arrays.binarySearch(arr, key) | Finds index of key (array must be sorted) | No |
Arrays.fill(arr, val) | Sets all elements to val | Yes |
Arrays.copyOf(arr, len) | Returns a new array of length len | No |
Arrays.copyOfRange(arr, from, to) | Returns a copy of a slice | No |
Arrays.equals(a, b) | True if same length and same elements | No |
Arrays.deepEquals(a, b) | Like equals but for nested arrays | No |
Arrays.toString(arr) | Returns a readable string | No |
Arrays.deepToString(arr) | Readable string for nested arrays | No |
Arrays.asList(arr) | Fixed-size List view of the array | No |
Arrays.parallelSort(arr) | Multi-threaded sort (Java 8+) | Yes |
Under the Hood
Knowing which algorithm Arrays uses helps you pick the right method:
Arrays.sort()on primitives — dual-pivot Quicksort (introduced in Java 7). Average O(n log n), worst case O(n²) in theory but crafted to avoid common adversarial inputs. Not stable (equal primitives may be reordered, but since primitives are indistinguishable by identity that doesn’t matter).Arrays.sort()on objects — TimSort, a hybrid merge/insertion sort. O(n log n) worst case, O(n) best case on nearly-sorted data. Stable — equal elements keep their original order, which matters when sorting objects.Arrays.parallelSort()— usesForkJoinPool.commonPool(). Arrays smaller than the threshold sort sequentially. On large arrays with available CPU cores the speedup can be dramatic.Arrays.copyOf()/Arrays.copyOfRange()— delegate toSystem.arraycopy()under the hood, which is a native intrinsic. It moves raw memory rather than looping in Java bytecode, making it very fast.Arrays.binarySearch()— standard binary search, O(log n). If you call it on an unsorted array, the JVM won’t throw an exception — you just get a wrong answer silently. Sort first, always.
Related Topics
- Arrays — the foundation: how to declare, initialize, and traverse arrays before using utility methods
- Multidimensional Arrays — work with 2D and 3D arrays, where
deepEqualsanddeepToStringbecome essential - Sorting Collections — sorting
Listand other collections withCollections.sort()andComparator - Comparable — implement natural ordering so your custom objects sort correctly with
Arrays.sort() - ArrayList — the flexible, resizable alternative when
Arrays.asList()isn’t enough - Stream API —
Arrays.stream()lets you pipe an array directly into the Stream pipeline for filter/map/reduce operations