The java.util.Arrays class is a powerful utility toolkit containing static helper methods for manipulating, sorting, searching, comparing, and printing Java arrays efficiently.
java.util.Arrays Methodsimport java.util.Arrays;
public class ArraysUtilityDemo {
public static void main(String[] args) {
int[] scores = { 85, 42, 99, 14, 76 };
// 1. Arrays.toString() - Clean formatted printing:
System.out.println("Original: " + Arrays.toString(scores)); // [85, 42, 99, 14, 76]
// 2. Arrays.sort() - High-speed Dual-Pivot Quicksort:
Arrays.sort(scores);
System.out.println("Sorted: " + Arrays.toString(scores)); // [14, 42, 76, 85, 99]
// 3. Arrays.binarySearch() - O(log n) lookup (Requires sorted array!):
int index = Arrays.binarySearch(scores, 76);
System.out.println("Index of 76: " + index); // Index 2
// 4. Arrays.copyOf() - Deep cloning and resizing:
int[] expanded = Arrays.copyOf(scores, 7);
System.out.println("Expanded (length 7): " + Arrays.toString(expanded)); // [14, 42, 76, 85, 99, 0, 0]
// 5. Arrays.fill() - Batch initialization:
int[] flags = new int[5];
Arrays.fill(flags, 1);
System.out.println("Filled flags: " + Arrays.toString(flags)); // [1, 1, 1, 1, 1]
// 6. Arrays.equals() - Value-based equality:
int[] a1 = { 1, 2, 3 };
int[] a2 = { 1, 2, 3 };
System.out.println("Arrays equal: " + Arrays.equals(a1, a2)); // true
}
}
Arrays.deepToString()Calling standard Arrays.toString() on a 2D array merely prints internal memory hashcodes. Use Arrays.deepToString() for formatted 2D/3D grids:
int[][] matrix = { { 1, 2 }, { 3, 4 } };
System.out.println(Arrays.deepToString(matrix)); // [[1, 2], [3, 4]]
Exam Question: "What does Arrays.binarySearch() return if the target element does NOT exist in the array?"
Answer: It returns a negative integer: -(insertion point) - 1, where the "insertion point" is the index position where the element would have been inserted to maintain sorted order. For example, if searching for 50 in [14, 42, 76, 85, 99], it should go at index 2, so it returns -(2) - 1 = -3.
Now let us explore how the terminal passes arguments to a Java program via String[] args. Proceed to: Command Line Arguments →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Array creation and memory.
Sorting and searching lists.
Custom object sorting.
Terminal string arrays.