Arrays Class

Naveen AnamaneniUpdated · 4 min read

You could write a loop to print, sort or search an array every time, but you shouldn't have to. Java's java.util.Arrays class is a toolbox of ready-made, well-tested methods for arrays. All of them are static, so you call them on the class: Arrays.sort(marks).

The Methods You'll Use Most

MethodDoesExample result
Arrays.toString(a)Text form of the array[78, 92, 86]
Arrays.sort(a)Sorts in place, smallest firsta becomes [78, 86, 92]
Arrays.binarySearch(a, key)Finds key in a sorted arrayindex, or a negative number
Arrays.fill(a, value)Sets every element to one value[0, 0, 0]
Arrays.equals(a, b)Same length and same values?true / false
Arrays.copyOf(a, n)New array of length nsee "Copying and Cloning Arrays"
Arrays.asList(...)A fixed-size List view[Pune, Goa]
Arrays.deepToString(grid)Text form of a 2D array[[1, 2], [3, 4]]

Sort, Search, Fill, Compare

Toolbox.java▶ Try it
import java.util.Arrays;
 
public class Toolbox {
    public static void main(String[] args) {
        int[] marks = {86, 64, 92, 78};
        Arrays.sort(marks);
        System.out.println("Sorted: " + Arrays.toString(marks));
        System.out.println("92 is at index " + Arrays.binarySearch(marks, 92));
        int[] seats = new int[5];
        Arrays.fill(seats, -1);
        System.out.println("Seats: " + Arrays.toString(seats));
        int[] same = {64, 78, 86, 92};
        System.out.println("equals: " + Arrays.equals(marks, same));
        System.out.println("==:     " + (marks == same));
    }
}
Output
Sorted: [64, 78, 86, 92]
92 is at index 3
Seats: [-1, -1, -1, -1, -1]
equals: true
==:     false

How it works

  1. Line 6 sorts marks in place: the array itself changes; nothing is returned.
  2. Line 8 searches the sorted array; 92 is at index 3.
  3. Line 10 sets every seat to -1, a common "not assigned" marker.
  4. Lines 13 and 14: Arrays.equals compares the values; == checks whether they're the same array, and they aren't.

Try it yourself: search for 80 with binarySearch. What number comes back?

Two Traps

binarySearch needs a sorted array. On an unsorted array, the result is meaningless. When the key isn't found, it returns -(insertionPoint) - 1: a negative number that tells you where the key would go. For 80 in [64, 78, 86, 92], it would go at index 2, so the result is -3.

Arrays.asList has a fixed size. It returns a List backed by the array: you can change elements with set, but add or remove throws UnsupportedOperationException. For a list you can grow, write new ArrayList<>(Arrays.asList(...)) (collections are covered later in the course).

Sorting Text and Part of an Array

Arrays.sort also sorts String[] alphabetically, and Arrays.sort(a, from, to) sorts just a range. For descending order or custom orders, you'll pass a comparator once you've learned lambdas, later in the course.

Common Mistakes

Printing an array with println(a). Use Arrays.toString(a).

Comparing arrays with == or a.equals(b). Both check whether it's the same array. Use Arrays.equals(a, b).

Searching an unsorted array. Sort first, or loop through it yourself.

Interview Corner

What does Arrays.binarySearch return if the key is not found?

A negative number, -(insertionPoint) - 1, where insertionPoint is the index at which the key would be inserted to keep the array sorted. The array must already be sorted, or the result is undefined.

Why can't you add elements to the list returned by Arrays.asList?

It's a fixed-size view backed by the original array, so its size can't change. set works and writes through to the array, but add and remove throw UnsupportedOperationException. Wrap it in new ArrayList<>(...) to get a resizable list.

Practice

  1. Easy: Sort {"Mysuru", "Agra", "Kochi", "Delhi"} and print it with Arrays.toString.
  2. Harder: Read 5 numbers, sort them, and print the smallest, the largest and the middle (median) value.

Quick check: Arrays class

4 questions
1What does Arrays.sort(a) return?
2What must be true before calling binarySearch?
3Which compares the contents of two arrays?
4What happens when you call add on the list from Arrays.asList("Pune", "Goa")?

Key Takeaways

Was this tutorial helpful?

Lesson 77 of 482