Arrays Utility Class in Java
Introduction
The java.util.Arrays class is a powerful utility in Java that provides static methods to manipulate, search, sort, and print arrays efficiently. Using these built-in methods instead of manual loops makes your code cleaner, safer, and more readable.
Core Concepts
- Utility Class: All methods in
java.util.Arraysarestatic. You do not need to create an object of theArraysclass; you call them directly usingArrays.methodName(). - Member of Collections Framework: It is designed to work seamlessly with Java arrays, providing bridges to other structures like
List. - Null Safety: Most methods will throw a
NullPointerExceptionif you pass anullarray.
Essential Methods Summary
| Method | Description |
| :--- | :--- |
| sort(array) | Sorts the entire array in ascending order (or a specified range). |
| binarySearch(array, key) | Searches for a specific value in a sorted array; returns the index. |
| toString(array) | Returns a human-readable string representation of the array contents. |
| equals(arr1, arr2) | Compares two arrays for deep equality (same elements in same order). |
| fill(array, value) | Assigns a specified value to every element of the array. |
| copyOf(array, newLength) | Creates a new array, copied from the original, with a new size. |
| asList(array) | Returns a fixed-size List view backed by the specified array. |
Quick Implementation Examples
1. Sorting and Printing
Always use Arrays.toString() when printing; printing an array directly will only display its memory reference (e.g., [I@3feba861).
import java.util.Arrays;
public class ArraySortExample {
public static void main(String[] args) {
int[] numbers = {5, 2, 9, 1, 3};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
// Output: [1, 2, 3, 5, 9]
}
}
2. Searching
The array must be sorted before performing a binary search.
import java.util.Arrays;
public class ArraySearchExample {
public static void main(String[] args) {
int[] sortedNumbers = {1, 2, 3, 5, 9};
int index = Arrays.binarySearch(sortedNumbers, 5);
System.out.println("Index of 5 is: " + index);
// Output: Index of 5 is: 3
}
}
3. Filling Arrays
Useful for initializing or resetting an array.
import java.util.Arrays;
public class ArrayFillExample {
public static void main(String[] args) {
int[] data = new int[5];
Arrays.fill(data, 10);
System.out.println(Arrays.toString(data));
// Output: [10, 10, 10, 10, 10]
}
}
Best Practice Tip
Whenever you need to perform common tasks like copying, sorting, or searching, check the java.util.Arrays class first. Writing custom algorithms for these tasks is usually unnecessary and more prone to bugs than using the optimized, standard library methods.