Java Arrays Class Methods
Java Arrays Class Methods
The java.util.Arrays class is a utility class in Java that provides static methods for common array operations — sorting, searching, copying, comparing, filling, and converting arrays to strings. Before Arrays existed, developers had to write these operations from scratch every time. Now a single import gives you production-ready implementations of the most frequent array operations.
Every method in Arrays is static — you call them on the class name directly: Arrays.sort(arr), not arr.sort(). There is no need to create an instance.
Import Statement
import java.util.Arrays;This single import gives you access to all methods covered in this article. Arrays lives in java.util — the same package as ArrayList, HashMap, and Collections.
Complete Method Reference
| Method | What It Does |
|---|---|
sort(array) | Sorts array in ascending order — in place |
sort(array, from, to) | Sorts only the specified range |
sort(array, comparator) | Sorts object arrays using custom order |
binarySearch(array, key) | Searches a sorted array — returns index |
binarySearch(array, from, to, key) | Binary search on a specific range |
copyOf(array, newLength) | Creates a copy with a new length |
copyOfRange(array, from, to) | Copies a slice of an array |
fill(array, value) | Sets all elements to a single value |
fill(array, from, to, value) | Fills only a specific range |
equals(array1, array2) | Compares two 1D arrays element by element |
deepEquals(array1, array2) | Compares multi-dimensional arrays deeply |
toString(array) | Returns readable string of 1D array |
deepToString(array) | Returns readable string of multi-dimensional array |
stream(array) | Returns an IntStream / Stream from the array |
asList(array) | Converts object array to a fixed-size List |
1 — Arrays.sort()
Arrays.sort() sorts an array in ascending order, in place. For primitives, it uses a variant of Quicksort. For objects, it uses TimSort (stable merge sort). Both are O(n log n) average time.
// File: ArraysSortDemo.java
import java.util.Arrays;
import java.util.Comparator;
public class ArraysSortDemo {
public static void main(String[] args) {
// Sort int array (ascending by default)
int[] marks = {72, 91, 55, 88, 63, 79, 97, 45};
System.out.println("Before sort : " + Arrays.toString(marks));
Arrays.sort(marks);
System.out.println("After sort : " + Arrays.toString(marks));
System.out.println();
// Sort only a range — indices from (inclusive) to to (exclusive)
int[] prices = {999, 499, 1299, 299, 799, 1999, 149};
System.out.println("Before range sort : " + Arrays.toString(prices));
Arrays.sort(prices, 1, 4); // sort only indices 1, 2, 3
System.out.println("After range sort : " + Arrays.toString(prices));
// Only prices[1], prices[2], prices[3] are sorted — rest unchanged
System.out.println();
// Sort String array — lexicographic (dictionary) order
String[] cities = {"Mumbai", "Delhi", "Bengaluru", "Chennai", "Pune"};
System.out.println("Before sort : " + Arrays.toString(cities));
Arrays.sort(cities);
System.out.println("After sort : " + Arrays.toString(cities));
System.out.println();
// Sort String array in REVERSE order using Comparator
String[] names = {"Rohan", "Priya", "Sneha", "Karan", "Ananya"};
System.out.println("Before reverse sort: " + Arrays.toString(names));
Arrays.sort(names, Comparator.reverseOrder());
System.out.println("After reverse sort : " + Arrays.toString(names));
System.out.println();
// Sort by string length — custom Comparator
String[] words = {"Java", "Programming", "Is", "Fun", "Really"};
Arrays.sort(words, Comparator.comparingInt(String::length));
System.out.println("Sorted by length : " + Arrays.toString(words));
}
}Output:
Before sort : [72, 91, 55, 88, 63, 79, 97, 45]
After sort : [45, 55, 63, 72, 79, 88, 91, 97]
Before range sort : [999, 499, 1299, 299, 799, 1999, 149]
After range sort : [999, 299, 499, 1299, 799, 1999, 149]
Before sort : [Mumbai, Delhi, Bengaluru, Chennai, Pune]
After sort : [Bengaluru, Chennai, Delhi, Mumbai, Pune]
Before reverse sort: [Rohan, Priya, Sneha, Karan, Ananya]
After reverse sort : [Sneha, Rohan, Priya, Karan, Ananya]
Sorted by length : [Is, Fun, Java, Really, Programming]
Key points:
- ›
Arrays.sort(arr)modifies the original array — it is not a copy. Sort a copy first if you need the original order preserved. - ›Range sort
Arrays.sort(arr, from, to)sorts from indexfrominclusive totoexclusive. Elements outside the range are untouched. - ›
Comparator.reverseOrder()works only for object arrays — notint[]. To sort anint[]in reverse, copy toInteger[]first. - ›
Comparator.comparingInt(fn)lets you sort by any computed integer property.
2 — Arrays.binarySearch()
Arrays.binarySearch() performs a binary search on a sorted array and returns the index of the target element. If the element is not found, it returns a negative value: -(insertion point) - 1.
Important: The array must be sorted before calling binarySearch. If it is not sorted, the result is undefined.
// File: BinarySearchDemo.java
import java.util.Arrays;
public class BinarySearchDemo {
public static void main(String[] args) {
// binarySearch on sorted int array
int[] sortedPrices = {149, 299, 499, 799, 999, 1299, 1999};
System.out.println("Sorted array: " + Arrays.toString(sortedPrices));
System.out.println();
int idx1 = Arrays.binarySearch(sortedPrices, 499);
System.out.println("Search for 499 : index = " + idx1); // 2
int idx2 = Arrays.binarySearch(sortedPrices, 999);
System.out.println("Search for 999 : index = " + idx2); // 4
// Not found — returns negative value
int idx3 = Arrays.binarySearch(sortedPrices, 600);
System.out.println("Search for 600 : index = " + idx3);
// 600 would go between index 3 (799) and... wait, between 499(idx2) and 799(idx3)
// insertion point = 4 (between 499 and 799 after sorting)
// return value = -(4) - 1 = -5
System.out.println();
// Decode the not-found return value
if (idx3 < 0) {
int insertionPoint = -(idx3) - 1;
System.out.println("600 not found. Would be inserted at index: " + insertionPoint);
}
System.out.println();
// binarySearch on a range
int[] arr = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int rangeIdx = Arrays.binarySearch(arr, 2, 7, 60); // search indices 2-6 only
System.out.println("Range search (60 in idx 2-6): index = " + rangeIdx); // 5
System.out.println();
// binarySearch on sorted String array
String[] fruits = {"Apple", "Banana", "Grapes", "Mango", "Orange"};
System.out.println("String array: " + Arrays.toString(fruits));
System.out.println("Search 'Mango' : index = " + Arrays.binarySearch(fruits, "Mango"));
System.out.println("Search 'Papaya' : index = " + Arrays.binarySearch(fruits, "Papaya"));
}
}Output:
Sorted array: [149, 299, 499, 799, 999, 1299, 1999]
Search for 499 : index = 2
Search for 999 : index = 4
Search for 600 : index = -5
600 not found. Would be inserted at index: 4
Range search (60 in idx 2-6): index = 5
String array: [Apple, Banana, Grapes, Mango, Orange]
Search 'Mango' : index = 3
Search 'Papaya' : index = -6
Key points:
- ›Always sort before calling
binarySearch. Results are undefined on unsorted arrays. - ›When not found, the return value encodes where the element would be inserted:
insertionPoint = -(result) - 1. - ›Use this insertion point to insert into the correct sorted position without re-sorting the entire array.
- ›Time complexity is O(log n) — far faster than linear search O(n) for large arrays.
3 — Arrays.copyOf() and Arrays.copyOfRange()
Arrays.copyOf() creates a new array that is a copy of the original. You specify the new length — if it is shorter, the array is truncated; if longer, the extra slots are filled with default values (0 for int, null for objects).
Arrays.copyOfRange() copies a slice of the original array between two indices.
// File: ArraysCopyDemo.java
import java.util.Arrays;
public class ArraysCopyDemo {
public static void main(String[] args) {
int[] original = {10, 20, 30, 40, 50};
System.out.println("Original: " + Arrays.toString(original));
// copyOf — same length (exact copy)
int[] exactCopy = Arrays.copyOf(original, original.length);
System.out.println("Exact copy : " + Arrays.toString(exactCopy));
// copyOf — shorter (truncated)
int[] shorter = Arrays.copyOf(original, 3);
System.out.println("Shorter (3) : " + Arrays.toString(shorter));
// copyOf — longer (extra slots filled with 0)
int[] longer = Arrays.copyOf(original, 8);
System.out.println("Longer (8) : " + Arrays.toString(longer));
System.out.println();
// Why exact copy matters — modifying copy does NOT affect original
exactCopy[0] = 999;
System.out.println("After copy[0]=999:");
System.out.println(" Original : " + Arrays.toString(original));
System.out.println(" exactCopy : " + Arrays.toString(exactCopy));
System.out.println();
// copyOfRange — copies from index (inclusive) to index (exclusive)
int[] scores = {85, 90, 78, 92, 65, 88, 71, 95};
System.out.println("Scores: " + Arrays.toString(scores));
int[] topThree = Arrays.copyOfRange(scores, 0, 3); // indices 0,1,2
int[] middleFour = Arrays.copyOfRange(scores, 2, 6); // indices 2,3,4,5
int[] lastTwo = Arrays.copyOfRange(scores, 6, 8); // indices 6,7
System.out.println("Top 3 (0-2) : " + Arrays.toString(topThree));
System.out.println("Middle 4 (2-5) : " + Arrays.toString(middleFour));
System.out.println("Last 2 (6-7) : " + Arrays.toString(lastTwo));
System.out.println();
// Common pattern: sort a copy, keep original unsorted
int[] studentMarks = {72, 91, 55, 88, 63, 79};
int[] sortedCopy = Arrays.copyOf(studentMarks, studentMarks.length);
Arrays.sort(sortedCopy);
System.out.println("Original (rank order): " + Arrays.toString(studentMarks));
System.out.println("Sorted copy (for stats): " + Arrays.toString(sortedCopy));
}
}Output:
Original: [10, 20, 30, 40, 50]
Exact copy : [10, 20, 30, 40, 50]
Shorter (3) : [10, 20, 30]
Longer (8) : [10, 20, 30, 40, 50, 0, 0, 0]
After copy[0]=999:
Original : [10, 20, 30, 40, 50]
exactCopy : [999, 20, 30, 40, 50]
Scores: [85, 90, 78, 92, 65, 88, 71, 95]
Top 3 (0-2) : [85, 90, 78]
Middle 4 (2-5) : [78, 92, 65, 88]
Last 2 (6-7) : [71, 95]
Original (rank order): [72, 91, 55, 88, 63, 79]
Sorted copy (for stats): [55, 63, 72, 79, 88, 91]
Key points:
- ›
Arrays.copyOf()creates a completely independent copy — modifying the copy never affects the original. - ›The
longercopy shows howcopyOfextends arrays: new slots get default values. This is used to implement "resizable array" behaviour manually. - ›
copyOfRange(arr, from, to)—fromis inclusive,tois exclusive. The length of the result isto - from. - ›The most common use pattern:
int[] copy = Arrays.copyOf(original, original.length)before callingArrays.sort()on the copy, keeping the original intact.
4 — Arrays.fill()
Arrays.fill() sets every element of an array to the same value. It is faster and more readable than a loop. A range variant fills only the specified indices.
// File: ArraysFillDemo.java
import java.util.Arrays;
public class ArraysFillDemo {
public static void main(String[] args) {
// Fill entire array
int[] slots = new int[7];
Arrays.fill(slots, -1); // use -1 to mark "empty" or "unset"
System.out.println("Filled with -1 : " + Arrays.toString(slots));
// Fill entire boolean array with true
boolean[] attendance = new boolean[5];
Arrays.fill(attendance, true); // everyone present initially
System.out.println("All present : " + Arrays.toString(attendance));
// Fill a range — indices from (inclusive) to to (exclusive)
int[] zones = new int[10];
Arrays.fill(zones, 0); // start with all zeros
Arrays.fill(zones, 0, 3, 1); // zone 1: indices 0,1,2
Arrays.fill(zones, 3, 7, 2); // zone 2: indices 3,4,5,6
Arrays.fill(zones, 7, 10, 3); // zone 3: indices 7,8,9
System.out.println("Zone map : " + Arrays.toString(zones));
System.out.println();
// Practical use: reset an array to zeros between operations
int[] scores = {88, 72, 91, 65, 79};
System.out.println("Before reset: " + Arrays.toString(scores));
Arrays.fill(scores, 0);
System.out.println("After reset : " + Arrays.toString(scores));
// Fill a String array
String[] grid = new String[5];
Arrays.fill(grid, "EMPTY");
System.out.println("String fill : " + Arrays.toString(grid));
}
}Output:
Filled with -1 : [-1, -1, -1, -1, -1, -1, -1]
All present : [true, true, true, true, true]
Zone map : [1, 1, 1, 2, 2, 2, 2, 3, 3, 3]
Before reset: [88, 72, 91, 65, 79]
After reset : [0, 0, 0, 0, 0]
String fill : [EMPTY, EMPTY, EMPTY, EMPTY, EMPTY]
Key points:
- ›
Arrays.fill(arr, val)is equivalent to a loopfor (int i = 0; i < arr.length; i++) arr[i] = val— but more readable and slightly more efficient. - ›Range fill
Arrays.fill(arr, from, to, val)—frominclusive,toexclusive — fills a subset. - ›Common use cases: initialising arrays to sentinel values (
-1,0,Integer.MAX_VALUE), resetting arrays between test runs, creating pre-filled grids.
5 — Arrays.equals() and Arrays.deepEquals()
Arrays.equals() compares two arrays element by element and returns true if both have the same length and every corresponding element is equal. For multi-dimensional arrays, use Arrays.deepEquals() — equals() on a 2D array only compares row references, not values.
// File: ArraysEqualsDemo.java
import java.util.Arrays;
public class ArraysEqualsDemo {
public static void main(String[] args) {
// equals() — 1D arrays
int[] a = {1, 2, 3, 4, 5};
int[] b = {1, 2, 3, 4, 5}; // same values, different object
int[] c = {1, 2, 3, 4, 6}; // different last element
int[] d = {1, 2, 3}; // different length
System.out.println("1D Arrays.equals():");
System.out.println(" a equals b (same values) : " + Arrays.equals(a, b)); // true
System.out.println(" a equals c (diff last elem) : " + Arrays.equals(a, c)); // false
System.out.println(" a equals d (diff length) : " + Arrays.equals(a, d)); // false
System.out.println(" a == b (reference check) : " + (a == b)); // false
System.out.println();
// 2D arrays — equals() WRONG, deepEquals() CORRECT
int[][] m1 = {{1, 2}, {3, 4}};
int[][] m2 = {{1, 2}, {3, 4}};
System.out.println("2D array comparison:");
System.out.println(" Arrays.equals(m1, m2) : " + Arrays.equals(m1, m2)); // false — compares references
System.out.println(" Arrays.deepEquals(m1, m2) : " + Arrays.deepEquals(m1, m2)); // true — compares values
System.out.println();
// deepEquals() — nested arrays
String[][] names1 = {{"Priya", "Rohan"}, {"Sneha", "Karan"}};
String[][] names2 = {{"Priya", "Rohan"}, {"Sneha", "Karan"}};
String[][] names3 = {{"Priya", "Rohan"}, {"Sneha", "KARAN"}}; // KARAN vs Karan
System.out.println("deepEquals on String[][]:");
System.out.println(" names1 deepEquals names2: " + Arrays.deepEquals(names1, names2)); // true
System.out.println(" names1 deepEquals names3: " + Arrays.deepEquals(names1, names3)); // false
System.out.println();
// Null safety — both null is true, one null is false
int[] nullArr = null;
System.out.println(" equals(null, null) : " + Arrays.equals(null, null)); // true
System.out.println(" equals(a, null) : " + Arrays.equals(a, null)); // false
}
}Output:
1D Arrays.equals():
a equals b (same values) : true
a equals c (diff last elem) : false
a equals d (diff length) : false
a == b (reference check) : false
2D array comparison:
Arrays.equals(m1, m2) : false
Arrays.deepEquals(m1, m2) : true
deepEquals on String[][]:
names1 deepEquals names2: true
names1 deepEquals names3: false
equals(null, null) : true
equals(a, null) : false
Key points:
- ›
Arrays.equals()is for 1D arrays only. For 2D or deeper, always useArrays.deepEquals(). - ›
Arrays.equals(a, b)is null-safe — comparing two null arrays returnstrue, comparing a null with a non-null returnsfalse. - ›
a == bcompares references — it returnstrueonly if both variables point to the exact same array object.Arrays.equals()compares content.
6 — Arrays.toString() and Arrays.deepToString()
Arrays.toString() converts a 1D array to a human-readable string like [85, 90, 78]. Without it, printing an array directly gives a useless memory address. Arrays.deepToString() does the same for multi-dimensional arrays.
// File: ArraysToStringDemo.java
import java.util.Arrays;
public class ArraysToStringDemo {
public static void main(String[] args) {
// Without Arrays.toString — useless output
int[] marks = {85, 90, 78, 92, 65};
System.out.println("Direct print : " + marks); // [I@7852e922
System.out.println("Arrays.toString : " + Arrays.toString(marks)); // [85, 90, 78, 92, 65]
System.out.println();
// toString() for different types
double[] prices = {499.0, 1299.0, 2999.0};
boolean[] flags = {true, false, true, true};
String[] cities = {"Mumbai", "Delhi", "Pune"};
char[] letters = {'J', 'A', 'V', 'A'};
System.out.println("double[] : " + Arrays.toString(prices));
System.out.println("boolean[]: " + Arrays.toString(flags));
System.out.println("String[] : " + Arrays.toString(cities));
System.out.println("char[] : " + Arrays.toString(letters));
System.out.println();
// 2D — toString() fails, deepToString() works
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println("2D direct print : " + matrix);
System.out.println("toString (2D) : " + Arrays.toString(matrix)); // row references
System.out.println("deepToString (2D) : " + Arrays.deepToString(matrix)); // full content
System.out.println();
// 3D array
int[][][] cube = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};
System.out.println("3D deepToString: " + Arrays.deepToString(cube));
}
}Output:
Direct print : [I@7852e922
Arrays.toString : [85, 90, 78, 92, 65]
double[] : [499.0, 1299.0, 2999.0]
boolean[]: [true, false, true, true]
String[] : [Mumbai, Delhi, Pune]
char[] : [J, A, V, A]
2D direct print : [[I@1b6d3586
toString (2D) : [[I@4554617c, [I@74a14482]
deepToString (2D) : [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
3D deepToString: [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
Key points:
- ›
Arrays.toString()works on 1D arrays of any primitive or object type. - ›
Arrays.deepToString()works on any depth of nesting. Use it for 2D and 3D arrays. - ›These are the most important debugging tools for arrays — print your array state at every step when debugging.
- ›
toString(null)returns"null"safely — no exception thrown.
7 — Arrays.stream()
Arrays.stream() converts an array into a Stream (or IntStream, LongStream, DoubleStream for primitives), giving access to all Java 8+ stream operations — filter, map, reduce, sum, average, min, max, and collect.
// File: ArraysStreamDemo.java
import java.util.Arrays;
import java.util.stream.Collectors;
public class ArraysStreamDemo {
public static void main(String[] args) {
int[] scores = {72, 88, 91, 55, 78, 95, 63, 83};
// sum, average, min, max — available on IntStream
System.out.println("IntStream operations:");
System.out.println(" Sum : " + Arrays.stream(scores).sum());
System.out.printf( " Average : %.2f%n", Arrays.stream(scores).average().orElse(0));
System.out.println(" Min : " + Arrays.stream(scores).min().orElse(0));
System.out.println(" Max : " + Arrays.stream(scores).max().orElse(0));
System.out.println(" Count : " + Arrays.stream(scores).count());
System.out.println();
// filter — keep only scores above 75
System.out.println("Scores above 75:");
int[] highScores = Arrays.stream(scores)
.filter(s -> s > 75)
.toArray();
System.out.println(" " + Arrays.toString(highScores));
System.out.println();
// map — convert marks to percentage (out of 100)
System.out.println("Marks as percentage strings:");
Arrays.stream(scores)
.mapToObj(s -> s + "%")
.forEach(s -> System.out.print(s + " "));
System.out.println();
System.out.println();
// sort + limit — top 3 scores
System.out.println("Top 3 scores:");
int[] top3 = Arrays.stream(scores)
.boxed()
.sorted((a, b) -> b - a) // descending
.limit(3)
.mapToInt(Integer::intValue)
.toArray();
System.out.println(" " + Arrays.toString(top3));
System.out.println();
// Stream on String array
String[] products = {"Laptop", "Mobile", "Tablet", "Earphones", "Keyboard"};
System.out.println("Products starting with 'L' or 'M':");
Arrays.stream(products)
.filter(p -> p.startsWith("L") || p.startsWith("M"))
.forEach(p -> System.out.println(" " + p));
System.out.println();
// Collect to a List
java.util.List<String> shortProducts = Arrays.stream(products)
.filter(p -> p.length() <= 6)
.collect(Collectors.toList());
System.out.println("Short name products: " + shortProducts);
}
}Output:
IntStream operations:
Sum : 625
Average : 78.13
Min : 55
Max : 95
Count : 8
Scores above 75:
[88, 91, 78, 95, 83]
Marks as percentage strings:
72% 88% 91% 55% 78% 95% 63% 83%
Top 3 scores:
[95, 91, 88]
Products starting with 'L' or 'M':
Laptop
Mobile
Short name products: [Laptop, Mobile, Tablet]
Key points:
- ›
Arrays.stream(intArr)returnsIntStream— with built-insum(),average(),min(),max(). - ›
Arrays.stream(objectArr)returnsStream<T>— needs.collect()to materialise results. - ›A range variant exists:
Arrays.stream(arr, from, to)streams only the specified range. - ›Chaining stream operations replaces many loops with one readable expression.
8 — Arrays.asList()
Arrays.asList() converts an array of objects to a fixed-size List. The list is backed by the array — changes to the list reflect in the array and vice versa. You can modify existing elements but cannot add or remove elements.
// File: ArraysAsListDemo.java
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
public class ArraysAsListDemo {
public static void main(String[] args) {
// Convert String array to List
String[] cityArr = {"Mumbai", "Delhi", "Bengaluru", "Chennai"};
List<String> cityList = Arrays.asList(cityArr);
System.out.println("Array : " + Arrays.toString(cityArr));
System.out.println("List : " + cityList);
System.out.println("Size : " + cityList.size());
System.out.println("Contains 'Delhi': " + cityList.contains("Delhi"));
System.out.println();
// Modifying an element — reflects in both array and list
cityList.set(1, "DELHI");
System.out.println("After list.set(1, 'DELHI'):");
System.out.println(" Array : " + Arrays.toString(cityArr)); // changed too
System.out.println(" List : " + cityList);
System.out.println();
// Cannot add or remove — UnsupportedOperationException
try {
cityList.add("Pune");
} catch (UnsupportedOperationException e) {
System.out.println("Cannot add: UnsupportedOperationException");
}
try {
cityList.remove(0);
} catch (UnsupportedOperationException e) {
System.out.println("Cannot remove: UnsupportedOperationException");
}
System.out.println();
// To get a fully modifiable List — wrap in new ArrayList
List<String> mutableList = new ArrayList<>(Arrays.asList(cityArr));
mutableList.add("Pune");
mutableList.remove("Mumbai");
System.out.println("Mutable list: " + mutableList);
System.out.println();
// Useful for quick initialisation and searching
List<String> allowedRoles = Arrays.asList("ADMIN", "MANAGER", "VIEWER");
String userRole = "EDITOR";
System.out.println("Role '" + userRole + "' allowed: "
+ allowedRoles.contains(userRole)); // false
System.out.println("Role 'ADMIN' allowed: " + allowedRoles.contains("ADMIN")); // true
}
}Output:
Array : [Mumbai, Delhi, Bengaluru, Chennai]
List : [Mumbai, Delhi, Bengaluru, Chennai]
Size : 4
Contains 'Delhi': true
After list.set(1, 'DELHI'):
Array : [Mumbai, DELHI, Bengaluru, Chennai]
List : [Mumbai, DELHI, Bengaluru, Chennai]
Cannot add: UnsupportedOperationException
Cannot remove: UnsupportedOperationException
Mutable list: [DELHI, Bengaluru, Chennai, Pune]
Role 'EDITOR' allowed: false
Role 'ADMIN' allowed: true
Key points:
- ›
Arrays.asList()returns a fixed-size List — you can callset()but notadd()orremove(). - ›The list is backed by the array — they share the same data.
- ›For a fully independent, modifiable list:
new ArrayList<>(Arrays.asList(arr)). - ›
Arrays.asList()does not work with primitive arrays —Arrays.asList(intArray)givesList<int[]>, notList<Integer>. UseInteger[]or stream boxing instead.
Basic Example
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] numbers = {5, 2, 8, 1, 9};
System.out.println("Before sort: " + Arrays.toString(numbers));
Arrays.sort(numbers);
System.out.println("After sort : " + Arrays.toString(numbers));
int index = Arrays.binarySearch(numbers, 8);
System.out.println("Index of 8 : " + index);
int[] copy = Arrays.copyOf(numbers, 3);
System.out.println("First 3 : " + Arrays.toString(copy));
}
}Output
Before sort: [5, 2, 8, 1, 9] After sort : [1, 2, 5, 8, 9] Index of 8 : 3 First 3 : [1, 2, 5]
- ›
Arrays.toString()turns the raw array into a readable, comma-separated string — printing the array directly would show a memory address instead. - ›
Arrays.sort()rearrangesnumbersin ascending order, in place. - ›
Arrays.binarySearch()looks up8in the now-sorted array and returns its index —3. - ›
Arrays.copyOf()creates a brand-new array containing just the first three elements of the sorted array, leavingnumbersitself untouched.
Best Practices
Always sort before calling binarySearch. Calling binarySearch on an unsorted array gives unpredictable results — the method assumes the array is sorted. If your array might not be sorted, either sort it first or use a linear search.
Use Arrays.copyOf() before sorting when the original order matters. Arrays.sort() is destructive — it rearranges the original. If you need both the original order (for display, name mapping) and a sorted order (for ranking, statistics), create a copy first, sort the copy, and keep the original intact.
Prefer Arrays.deepToString() over Arrays.toString() when unsure of dimensions. deepToString() works correctly on both 1D and multi-dimensional arrays. Using it everywhere avoids the silent bug of printing [[I@7852e922] when you accidentally pass a 2D array.
Wrap Arrays.asList() result in new ArrayList<>() when you need to add or remove. The list returned by asList() throws UnsupportedOperationException on structural modification. If your code ever needs to grow or shrink the list, wrap it immediately: new ArrayList<>(Arrays.asList(arr)).
Common Mistakes
Mistake 1 — Calling binarySearch on Unsorted Array
int[] unsorted = {72, 45, 91, 38, 88};
int idx = Arrays.binarySearch(unsorted, 91);
System.out.println(idx); // undefined result — not guaranteed to be correct
// Fix — sort first
Arrays.sort(unsorted);
idx = Arrays.binarySearch(unsorted, 91);
System.out.println(idx); // correct index in sorted arrayMistake 2 — Using toString() on 2D Arrays
int[][] matrix = {{1, 2}, {3, 4}};
System.out.println(Arrays.toString(matrix)); // [[I@7852e922, [I@4554617c] — wrong
System.out.println(Arrays.deepToString(matrix)); // [[1, 2], [3, 4]] — correctMistake 3 — Forgetting that sort() Modifies the Original
int[] marks = {85, 72, 91, 63};
Arrays.sort(marks); // marks is now {63, 72, 85, 91} — original order gone
// If you need the original order (e.g., to map marks to student names):
int[] copy = Arrays.copyOf(marks, marks.length);
Arrays.sort(copy); // sort only the copyMistake 4 — Using asList() With Primitive Arrays
int[] primitiveArr = {1, 2, 3};
// Arrays.asList(primitiveArr) returns List<int[]> — not List<Integer>!
java.util.List<int[]> wrong = Arrays.asList(primitiveArr);
System.out.println(wrong.size()); // 1 — the list has ONE element: the int[] itself
// Fix — use Integer[] instead
Integer[] boxedArr = {1, 2, 3};
java.util.List<Integer> correct = Arrays.asList(boxedArr);
System.out.println(correct.size()); // 3 — three Integer elementsInterview Questions
Q1. What is the java.util.Arrays class and what is it used for?
java.util.Arrays is a utility class that provides static methods for common array operations. It offers sort, binary search, copy, fill, equality comparison, string conversion, and stream conversion. Every method is static — called on the class name, not on an array instance. It eliminates the need to write custom implementations of these operations from scratch. It is imported with import java.util.Arrays and is part of the Java standard library since Java 1.2.
Q2. What is the difference between Arrays.equals() and Arrays.deepEquals()?
Arrays.equals() compares two 1D arrays element by element and returns true if lengths match and all corresponding elements are equal. For multi-dimensional arrays, it only compares the row references — not the actual values inside the rows — giving wrong results. Arrays.deepEquals() recursively compares all elements at every nesting level, making it correct for 2D, 3D, and any depth of array. Always use deepEquals() for multi-dimensional arrays.
Q3. What happens when Arrays.binarySearch() does not find the element?
When the target is not found, binarySearch() returns a negative number calculated as -(insertionPoint) - 1, where insertionPoint is the index where the element would be inserted to keep the array sorted. To recover the insertion point: int pos = -(result) - 1. This allows callers to know both that the element is absent and exactly where to insert it. If the result is negative, the element is not in the array.
Q4. What is the difference between Arrays.sort() and Collections.sort()?
Arrays.sort() works on arrays — both primitive arrays (int[], double[]) and object arrays (String[]). For primitives, it uses a dual-pivot quicksort. For objects, it uses TimSort. Collections.sort() works on objects that implement List — such as ArrayList. Both use TimSort for objects and are O(n log n). For arrays, use Arrays.sort(); for ArrayList, use Collections.sort().
Q5. What does Arrays.copyOf() do differently from assigning one array to another?
Assigning int[] b = a makes both variables point to the same array object. Modifying b[0] changes a[0] too — they share the same memory. Arrays.copyOf(a, a.length) creates a completely new, independent array with the same values. Modifying the copy has no effect on the original. Use Arrays.copyOf() whenever you need an independent copy — especially before calling Arrays.sort() on data you want to preserve in its original order.
Q6. How does Arrays.stream() improve array processing?
Arrays.stream(arr) converts an array to a stream, enabling Java 8+ functional operations — filter, map, reduce, sorted, distinct, sum, average, min, max, count, and collect. This replaces multiple loops with a single readable expression. For int[], it returns IntStream with direct numeric aggregation methods. For object arrays, it returns Stream<T>. Operations are lazy — they execute only when a terminal operation (sum(), toArray(), collect()) is called.
FAQs
Does Arrays.sort() work on primitive arrays?
Yes. Arrays.sort(int[]), Arrays.sort(double[]), Arrays.sort(char[]) and all other primitive array types are supported. For primitive arrays, Arrays.sort() uses a dual-pivot quicksort algorithm. For object arrays, it uses TimSort (a stable, merge-sort-based algorithm). Comparator can only be used with object arrays — not primitive arrays.
Can you use Arrays.stream() on a 2D array?
Arrays.stream(int[][]) returns Stream<int[]> — a stream of row arrays, not a flat stream of individual integers. To get a flat stream of all integers in a 2D array, use Arrays.stream(matrix).flatMapToInt(Arrays::stream). This flattens all rows into a single IntStream.
What is the time complexity of Arrays.sort() and Arrays.binarySearch()?
Arrays.sort() is O(n log n) for both primitives and objects. Arrays.binarySearch() is O(log n) — it eliminates half the remaining search space with each comparison. Linear search is O(n). For a sorted array of 1 million elements, binary search requires at most 20 comparisons; linear search requires up to 1 million.
Is Arrays.asList() backed by the original array?
Yes. The List returned by Arrays.asList(arr) is directly backed by the array. Calling list.set(i, value) changes both the list and the underlying array at the same position. Calling list.add() or list.remove() throws UnsupportedOperationException because the underlying array cannot grow or shrink. To get a fully independent, modifiable list, wrap with new ArrayList<>(Arrays.asList(arr)).
Does Arrays.fill() work on multi-dimensional arrays?
Arrays.fill(int[][] arr, value) is not directly available. Calling Arrays.fill(arr, value) on a 2D array fills each row slot with value — but value must be an int[] reference, not an int. To fill all cells of a 2D array with a single integer, loop over rows: for (int[] row : arr) Arrays.fill(row, value).
Summary
java.util.Arrays is one of the most practically useful utility classes in Java. Sorting with Arrays.sort(), searching with Arrays.binarySearch(), copying with Arrays.copyOf(), filling with Arrays.fill(), comparing with Arrays.equals() / deepEquals(), printing with Arrays.toString() / deepToString(), and streaming with Arrays.stream() — together these eight methods cover virtually every array operation a developer needs.
The most common production mistakes: calling binarySearch on an unsorted array, using toString on a 2D array, sorting in place when the original order needs to be preserved, and using asList with a primitive array. Knowing these pitfalls and their fixes separates developers who understand these tools from those who only memorise the method names.
What to Read Next
Learn what happens when you pass an array into a method.
Practice Programs
Put this topic into practice — each program has full code, output and a step-by-step explanation you can run online.
Sorts an array into ascending order using the built-in sort method.
Searches a sorted array for a target value by repeatedly halving the search range.
Creates an independent copy of an array.
Checks whether two arrays hold the same elements in the same order.
Declares an array and prints every element it holds.