The Java Arrays Class
Why a Utility Class?
Arrays themselves don't come with built-in methods for sorting, searching, printing, or comparing — an array is a very bare-bones structure. Instead, Java provides java.util.Arrays, a utility class full of static helper methods that operate on arrays. You never create an instance of Arrays — you just call its methods directly, like Arrays.sort(...).
import java.util.Arrays;
Arrays.sort() — Sorting in Place
int[] numbers = {5, 2, 8, 1, 9};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));[1, 2, 5, 8, 9]
Arrays.toString() — Actually Printing an Array
A very common beginner surprise: printing an array directly with println doesn't show its contents at all.
Broken: printing the array directly
int[] numbers = {1, 2, 5, 8, 9};
System.out.println(numbers);[I@1b6d3586
Fixed: using Arrays.toString()
int[] numbers = {1, 2, 5, 8, 9};
System.out.println(Arrays.toString(numbers));
int[][] grid = {{1, 2}, {3, 4}};
System.out.println(Arrays.deepToString(grid));[1, 2, 5, 8, 9] [[1, 2], [3, 4]]
Arrays.equals() — Comparing Contents
Arrays are objects, so using == on two arrays compares whether they're the SAME object in memory — not whether they contain the same values. Arrays.equals() compares element-by-element content instead.
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
System.out.println(a == b); // reference comparison
System.out.println(Arrays.equals(a, b)); // content comparisonfalse true
Arrays.fill() — Filling Every Slot
int[] scores = new int[5]; Arrays.fill(scores, 100); System.out.println(Arrays.toString(scores));
[100, 100, 100, 100, 100]
Arrays.binarySearch() — Fast Lookup on Sorted Arrays
int[] numbers = {1, 2, 5, 8, 9};
int index = Arrays.binarySearch(numbers, 8);
System.out.println("Found at index: " + index);Found at index: 3
Arrays.asList() — A Fixed-Size List View
String[] names = {"Amina", "Chen", "Diego"};
List<String> nameList = Arrays.asList(names);
System.out.println(nameList);[Amina, Chen, Diego]
Quick Reference
Method | Purpose |
Arrays.sort(arr) | Sorts the array in place, ascending order |
Arrays.toString(arr) | Returns a readable [a, b, c] string of contents |
Arrays.deepToString(arr) | Like toString(), but for nested/multidimensional arrays |
Arrays.equals(a, b) | Compares contents of two arrays for equality |
Arrays.fill(arr, value) | Sets every element to the given value |
Arrays.binarySearch(arr, value) | Finds the index of value in a SORTED array |
Arrays.asList(arr) | Returns a fixed-size List view backed by the array |
Practice Exercises
Sort an int array and print it correctly using Arrays.toString().
Compare two arrays with == and Arrays.equals() and explain the different results.
Use Arrays.fill() to initialize a 10-element array with the value -1, then use Arrays.binarySearch() after sorting a separate array to find a specific value.