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
1import 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.
1// File: ArraysSortDemo.java
2
3import java.util.Arrays;
4import java.util.Comparator;
5
6public class ArraysSortDemo {
7
8 public static void main(String[] args) {
9
10 // Sort int array (ascending by default)
11 int[] marks = {72, 91, 55, 88, 63, 79, 97, 45};
12 System.out.println("Before sort : " + Arrays.toString(marks));
13 Arrays.sort(marks);
14 System.out.println("After sort : " + Arrays.toString(marks));
15
16 System.out.println();
17
18 // Sort only a range — indices from (inclusive) to to (exclusive)
19 int[] prices = {999, 499, 1299, 299, 799, 1999, 149};
20 System.out.println("Before range sort : " + Arrays.toString(prices));
21 Arrays.sort(prices, 1, 4); // sort only indices 1, 2, 3
22 System.out.println("After range sort : " + Arrays.toString(prices));
23 // Only prices[1], prices[2], prices[3] are sorted — rest unchanged
24
25 System.out.println();
26
27 // Sort String array — lexicographic (dictionary) order
28 String[] cities = {"Mumbai", "Delhi", "Bengaluru", "Chennai", "Pune"};
29 System.out.println("Before sort : " + Arrays.toString(cities));
30 Arrays.sort(cities);
31 System.out.println("After sort : " + Arrays.toString(cities));
32
33 System.out.println();
34
35 // Sort String array in REVERSE order using Comparator
36 String[] names = {"Rohan", "Priya", "Sneha", "Karan", "Ananya"};
37 System.out.println("Before reverse sort: " + Arrays.toString(names));
38 Arrays.sort(names, Comparator.reverseOrder());
39 System.out.println("After reverse sort : " + Arrays.toString(names));
40
41 System.out.println();
42
43 // Sort by string length — custom Comparator
44 String[] words = {"Java", "Programming", "Is", "Fun", "Really"};
45 Arrays.sort(words, Comparator.comparingInt(String::length));
46 System.out.println("Sorted by length : " + Arrays.toString(words));
47 }
48}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.
1// File: BinarySearchDemo.java
2
3import java.util.Arrays;
4
5public class BinarySearchDemo {
6
7 public static void main(String[] args) {
8
9 // binarySearch on sorted int array
10 int[] sortedPrices = {149, 299, 499, 799, 999, 1299, 1999};
11 System.out.println("Sorted array: " + Arrays.toString(sortedPrices));
12 System.out.println();
13
14 int idx1 = Arrays.binarySearch(sortedPrices, 499);
15 System.out.println("Search for 499 : index = " + idx1); // 2
16
17 int idx2 = Arrays.binarySearch(sortedPrices, 999);
18 System.out.println("Search for 999 : index = " + idx2); // 4
19
20 // Not found — returns negative value
21 int idx3 = Arrays.binarySearch(sortedPrices, 600);
22 System.out.println("Search for 600 : index = " + idx3);
23 // 600 would go between index 3 (799) and... wait, between 499(idx2) and 799(idx3)
24 // insertion point = 4 (between 499 and 799 after sorting)
25 // return value = -(4) - 1 = -5
26
27 System.out.println();
28
29 // Decode the not-found return value
30 if (idx3 < 0) {
31 int insertionPoint = -(idx3) - 1;
32 System.out.println("600 not found. Would be inserted at index: " + insertionPoint);
33 }
34
35 System.out.println();
36
37 // binarySearch on a range
38 int[] arr = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
39 int rangeIdx = Arrays.binarySearch(arr, 2, 7, 60); // search indices 2-6 only
40 System.out.println("Range search (60 in idx 2-6): index = " + rangeIdx); // 5
41
42 System.out.println();
43
44 // binarySearch on sorted String array
45 String[] fruits = {"Apple", "Banana", "Grapes", "Mango", "Orange"};
46 System.out.println("String array: " + Arrays.toString(fruits));
47 System.out.println("Search 'Mango' : index = " + Arrays.binarySearch(fruits, "Mango"));
48 System.out.println("Search 'Papaya' : index = " + Arrays.binarySearch(fruits, "Papaya"));
49 }
50}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.
1// File: ArraysCopyDemo.java
2
3import java.util.Arrays;
4
5public class ArraysCopyDemo {
6
7 public static void main(String[] args) {
8
9 int[] original = {10, 20, 30, 40, 50};
10 System.out.println("Original: " + Arrays.toString(original));
11
12 // copyOf — same length (exact copy)
13 int[] exactCopy = Arrays.copyOf(original, original.length);
14 System.out.println("Exact copy : " + Arrays.toString(exactCopy));
15
16 // copyOf — shorter (truncated)
17 int[] shorter = Arrays.copyOf(original, 3);
18 System.out.println("Shorter (3) : " + Arrays.toString(shorter));
19
20 // copyOf — longer (extra slots filled with 0)
21 int[] longer = Arrays.copyOf(original, 8);
22 System.out.println("Longer (8) : " + Arrays.toString(longer));
23
24 System.out.println();
25
26 // Why exact copy matters — modifying copy does NOT affect original
27 exactCopy[0] = 999;
28 System.out.println("After copy[0]=999:");
29 System.out.println(" Original : " + Arrays.toString(original));
30 System.out.println(" exactCopy : " + Arrays.toString(exactCopy));
31
32 System.out.println();
33
34 // copyOfRange — copies from index (inclusive) to index (exclusive)
35 int[] scores = {85, 90, 78, 92, 65, 88, 71, 95};
36 System.out.println("Scores: " + Arrays.toString(scores));
37
38 int[] topThree = Arrays.copyOfRange(scores, 0, 3); // indices 0,1,2
39 int[] middleFour = Arrays.copyOfRange(scores, 2, 6); // indices 2,3,4,5
40 int[] lastTwo = Arrays.copyOfRange(scores, 6, 8); // indices 6,7
41
42 System.out.println("Top 3 (0-2) : " + Arrays.toString(topThree));
43 System.out.println("Middle 4 (2-5) : " + Arrays.toString(middleFour));
44 System.out.println("Last 2 (6-7) : " + Arrays.toString(lastTwo));
45
46 System.out.println();
47
48 // Common pattern: sort a copy, keep original unsorted
49 int[] studentMarks = {72, 91, 55, 88, 63, 79};
50 int[] sortedCopy = Arrays.copyOf(studentMarks, studentMarks.length);
51 Arrays.sort(sortedCopy);
52 System.out.println("Original (rank order): " + Arrays.toString(studentMarks));
53 System.out.println("Sorted copy (for stats): " + Arrays.toString(sortedCopy));
54 }
55}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.
1// File: ArraysFillDemo.java
2
3import java.util.Arrays;
4
5public class ArraysFillDemo {
6
7 public static void main(String[] args) {
8
9 // Fill entire array
10 int[] slots = new int[7];
11 Arrays.fill(slots, -1); // use -1 to mark "empty" or "unset"
12 System.out.println("Filled with -1 : " + Arrays.toString(slots));
13
14 // Fill entire boolean array with true
15 boolean[] attendance = new boolean[5];
16 Arrays.fill(attendance, true); // everyone present initially
17 System.out.println("All present : " + Arrays.toString(attendance));
18
19 // Fill a range — indices from (inclusive) to to (exclusive)
20 int[] zones = new int[10];
21 Arrays.fill(zones, 0); // start with all zeros
22 Arrays.fill(zones, 0, 3, 1); // zone 1: indices 0,1,2
23 Arrays.fill(zones, 3, 7, 2); // zone 2: indices 3,4,5,6
24 Arrays.fill(zones, 7, 10, 3); // zone 3: indices 7,8,9
25 System.out.println("Zone map : " + Arrays.toString(zones));
26
27 System.out.println();
28
29 // Practical use: reset an array to zeros between operations
30 int[] scores = {88, 72, 91, 65, 79};
31 System.out.println("Before reset: " + Arrays.toString(scores));
32 Arrays.fill(scores, 0);
33 System.out.println("After reset : " + Arrays.toString(scores));
34
35 // Fill a String array
36 String[] grid = new String[5];
37 Arrays.fill(grid, "EMPTY");
38 System.out.println("String fill : " + Arrays.toString(grid));
39 }
40}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.
1// File: ArraysEqualsDemo.java
2
3import java.util.Arrays;
4
5public class ArraysEqualsDemo {
6
7 public static void main(String[] args) {
8
9 // equals() — 1D arrays
10 int[] a = {1, 2, 3, 4, 5};
11 int[] b = {1, 2, 3, 4, 5}; // same values, different object
12 int[] c = {1, 2, 3, 4, 6}; // different last element
13 int[] d = {1, 2, 3}; // different length
14
15 System.out.println("1D Arrays.equals():");
16 System.out.println(" a equals b (same values) : " + Arrays.equals(a, b)); // true
17 System.out.println(" a equals c (diff last elem) : " + Arrays.equals(a, c)); // false
18 System.out.println(" a equals d (diff length) : " + Arrays.equals(a, d)); // false
19 System.out.println(" a == b (reference check) : " + (a == b)); // false
20
21 System.out.println();
22
23 // 2D arrays — equals() WRONG, deepEquals() CORRECT
24 int[][] m1 = {{1, 2}, {3, 4}};
25 int[][] m2 = {{1, 2}, {3, 4}};
26
27 System.out.println("2D array comparison:");
28 System.out.println(" Arrays.equals(m1, m2) : " + Arrays.equals(m1, m2)); // false — compares references
29 System.out.println(" Arrays.deepEquals(m1, m2) : " + Arrays.deepEquals(m1, m2)); // true — compares values
30
31 System.out.println();
32
33 // deepEquals() — nested arrays
34 String[][] names1 = {{"Priya", "Rohan"}, {"Sneha", "Karan"}};
35 String[][] names2 = {{"Priya", "Rohan"}, {"Sneha", "Karan"}};
36 String[][] names3 = {{"Priya", "Rohan"}, {"Sneha", "KARAN"}}; // KARAN vs Karan
37
38 System.out.println("deepEquals on String[][]:");
39 System.out.println(" names1 deepEquals names2: " + Arrays.deepEquals(names1, names2)); // true
40 System.out.println(" names1 deepEquals names3: " + Arrays.deepEquals(names1, names3)); // false
41
42 System.out.println();
43
44 // Null safety — both null is true, one null is false
45 int[] nullArr = null;
46 System.out.println(" equals(null, null) : " + Arrays.equals(null, null)); // true
47 System.out.println(" equals(a, null) : " + Arrays.equals(a, null)); // false
48 }
49}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.
1// File: ArraysToStringDemo.java
2
3import java.util.Arrays;
4
5public class ArraysToStringDemo {
6
7 public static void main(String[] args) {
8
9 // Without Arrays.toString — useless output
10 int[] marks = {85, 90, 78, 92, 65};
11 System.out.println("Direct print : " + marks); // [I@7852e922
12 System.out.println("Arrays.toString : " + Arrays.toString(marks)); // [85, 90, 78, 92, 65]
13
14 System.out.println();
15
16 // toString() for different types
17 double[] prices = {499.0, 1299.0, 2999.0};
18 boolean[] flags = {true, false, true, true};
19 String[] cities = {"Mumbai", "Delhi", "Pune"};
20 char[] letters = {'J', 'A', 'V', 'A'};
21
22 System.out.println("double[] : " + Arrays.toString(prices));
23 System.out.println("boolean[]: " + Arrays.toString(flags));
24 System.out.println("String[] : " + Arrays.toString(cities));
25 System.out.println("char[] : " + Arrays.toString(letters));
26
27 System.out.println();
28
29 // 2D — toString() fails, deepToString() works
30 int[][] matrix = {
31 {1, 2, 3},
32 {4, 5, 6},
33 {7, 8, 9}
34 };
35
36 System.out.println("2D direct print : " + matrix);
37 System.out.println("toString (2D) : " + Arrays.toString(matrix)); // row references
38 System.out.println("deepToString (2D) : " + Arrays.deepToString(matrix)); // full content
39
40 System.out.println();
41
42 // 3D array
43 int[][][] cube = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};
44 System.out.println("3D deepToString: " + Arrays.deepToString(cube));
45 }
46}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.
1// File: ArraysStreamDemo.java
2
3import java.util.Arrays;
4import java.util.stream.Collectors;
5
6public class ArraysStreamDemo {
7
8 public static void main(String[] args) {
9
10 int[] scores = {72, 88, 91, 55, 78, 95, 63, 83};
11
12 // sum, average, min, max — available on IntStream
13 System.out.println("IntStream operations:");
14 System.out.println(" Sum : " + Arrays.stream(scores).sum());
15 System.out.printf( " Average : %.2f%n", Arrays.stream(scores).average().orElse(0));
16 System.out.println(" Min : " + Arrays.stream(scores).min().orElse(0));
17 System.out.println(" Max : " + Arrays.stream(scores).max().orElse(0));
18 System.out.println(" Count : " + Arrays.stream(scores).count());
19
20 System.out.println();
21
22 // filter — keep only scores above 75
23 System.out.println("Scores above 75:");
24 int[] highScores = Arrays.stream(scores)
25 .filter(s -> s > 75)
26 .toArray();
27 System.out.println(" " + Arrays.toString(highScores));
28
29 System.out.println();
30
31 // map — convert marks to percentage (out of 100)
32 System.out.println("Marks as percentage strings:");
33 Arrays.stream(scores)
34 .mapToObj(s -> s + "%")
35 .forEach(s -> System.out.print(s + " "));
36 System.out.println();
37
38 System.out.println();
39
40 // sort + limit — top 3 scores
41 System.out.println("Top 3 scores:");
42 int[] top3 = Arrays.stream(scores)
43 .boxed()
44 .sorted((a, b) -> b - a) // descending
45 .limit(3)
46 .mapToInt(Integer::intValue)
47 .toArray();
48 System.out.println(" " + Arrays.toString(top3));
49
50 System.out.println();
51
52 // Stream on String array
53 String[] products = {"Laptop", "Mobile", "Tablet", "Earphones", "Keyboard"};
54 System.out.println("Products starting with 'L' or 'M':");
55 Arrays.stream(products)
56 .filter(p -> p.startsWith("L") || p.startsWith("M"))
57 .forEach(p -> System.out.println(" " + p));
58
59 System.out.println();
60
61 // Collect to a List
62 java.util.List<String> shortProducts = Arrays.stream(products)
63 .filter(p -> p.length() <= 6)
64 .collect(Collectors.toList());
65 System.out.println("Short name products: " + shortProducts);
66 }
67}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.
1// File: ArraysAsListDemo.java
2
3import java.util.Arrays;
4import java.util.ArrayList;
5import java.util.List;
6
7public class ArraysAsListDemo {
8
9 public static void main(String[] args) {
10
11 // Convert String array to List
12 String[] cityArr = {"Mumbai", "Delhi", "Bengaluru", "Chennai"};
13 List<String> cityList = Arrays.asList(cityArr);
14
15 System.out.println("Array : " + Arrays.toString(cityArr));
16 System.out.println("List : " + cityList);
17 System.out.println("Size : " + cityList.size());
18 System.out.println("Contains 'Delhi': " + cityList.contains("Delhi"));
19
20 System.out.println();
21
22 // Modifying an element — reflects in both array and list
23 cityList.set(1, "DELHI");
24 System.out.println("After list.set(1, 'DELHI'):");
25 System.out.println(" Array : " + Arrays.toString(cityArr)); // changed too
26 System.out.println(" List : " + cityList);
27
28 System.out.println();
29
30 // Cannot add or remove — UnsupportedOperationException
31 try {
32 cityList.add("Pune");
33 } catch (UnsupportedOperationException e) {
34 System.out.println("Cannot add: UnsupportedOperationException");
35 }
36
37 try {
38 cityList.remove(0);
39 } catch (UnsupportedOperationException e) {
40 System.out.println("Cannot remove: UnsupportedOperationException");
41 }
42
43 System.out.println();
44
45 // To get a fully modifiable List — wrap in new ArrayList
46 List<String> mutableList = new ArrayList<>(Arrays.asList(cityArr));
47 mutableList.add("Pune");
48 mutableList.remove("Mumbai");
49 System.out.println("Mutable list: " + mutableList);
50
51 System.out.println();
52
53 // Useful for quick initialisation and searching
54 List<String> allowedRoles = Arrays.asList("ADMIN", "MANAGER", "VIEWER");
55 String userRole = "EDITOR";
56 System.out.println("Role '" + userRole + "' allowed: "
57 + allowedRoles.contains(userRole)); // false
58 System.out.println("Role 'ADMIN' allowed: " + allowedRoles.contains("ADMIN")); // true
59 }
60}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.
Real-World Example — Student Grade Processing System
The Business Problem
A school's result processing system receives raw marks for an exam, needs to sort for ranking, search for specific scores, compute statistics, compare current and previous results, and produce a final grade report. Every operation maps to an Arrays method.
1// File: GradeProcessingSystem.java
2
3import java.util.Arrays;
4
5public class GradeProcessingSystem {
6
7 private static final String[] STUDENT_NAMES = {
8 "Priya Sharma", "Rohan Mehta", "Sneha Rao",
9 "Karan Singh", "Ananya Iyer", "Deepak Joshi",
10 "Meera Nair", "Suresh Yadav"
11 };
12
13 private static final int[] CURRENT_MARKS = {85, 72, 91, 63, 95, 55, 79, 88};
14 private static final int[] PREVIOUS_MARKS = {82, 75, 91, 60, 92, 55, 79, 88};
15
16 public static String assignGrade(int mark) {
17 if (mark >= 90) return "A+";
18 if (mark >= 75) return "A";
19 if (mark >= 60) return "B";
20 if (mark >= 45) return "C";
21 return "FAIL";
22 }
23
24 public static void main(String[] args) {
25
26 int count = CURRENT_MARKS.length;
27
28 System.out.println("╔══════════════════════════════════════════╗");
29 System.out.println("║ EXAM RESULT PROCESSING SYSTEM ║");
30 System.out.println("╚══════════════════════════════════════════╝");
31
32 // Step 1 — Check if result changed since last exam using Arrays.equals()
33 boolean unchanged = Arrays.equals(CURRENT_MARKS, PREVIOUS_MARKS);
34 System.out.println("\n[1] Results same as previous exam: " + unchanged);
35
36 // Step 2 — Statistics using Arrays.stream()
37 double average = Arrays.stream(CURRENT_MARKS).average().orElse(0);
38 int highest = Arrays.stream(CURRENT_MARKS).max().orElse(0);
39 int lowest = Arrays.stream(CURRENT_MARKS).min().orElse(0);
40 int passed = (int) Arrays.stream(CURRENT_MARKS).filter(m -> m >= 45).count();
41
42 System.out.println("\n[2] Statistics:");
43 System.out.printf(" Average: %.2f | Highest: %d | Lowest: %d%n",
44 average, highest, lowest);
45 System.out.println(" Students passed: " + passed + "/" + count);
46
47 // Step 3 — Create sorted copy for ranking (keep original for name mapping)
48 int[] sortedCopy = Arrays.copyOf(CURRENT_MARKS, count);
49 Arrays.sort(sortedCopy);
50 System.out.println("\n[3] Marks in ascending order (for ranking):");
51 System.out.println(" " + Arrays.toString(sortedCopy));
52
53 // Step 4 — Find rank using Arrays.binarySearch() on sorted copy
54 System.out.println("\n[4] Rank lookup:");
55 for (int i = 0; i < count; i++) {
56 int mark = CURRENT_MARKS[i];
57 int sortedIdx = Arrays.binarySearch(sortedCopy, mark);
58 // Rank from top = count - sortedIdx
59 int rank = count - sortedIdx;
60 System.out.printf(" %-15s Mark: %3d | Rank: %d%n",
61 STUDENT_NAMES[i], mark, rank);
62 }
63
64 // Step 5 — Full grade report
65 System.out.println("\n[5] Complete Grade Report:");
66 System.out.println("─".repeat(50));
67 System.out.printf(" %-15s %4s %4s %s%n", "Name", "Curr", "Prev", "Grade");
68 System.out.println("─".repeat(50));
69
70 for (int i = 0; i < count; i++) {
71 int curr = CURRENT_MARKS[i];
72 int prev = PREVIOUS_MARKS[i];
73 String trend = curr > prev ? "↑" : curr < prev ? "↓" : "=";
74 System.out.printf(" %-15s %4d %4d %-3s %s%n",
75 STUDENT_NAMES[i], curr, prev, assignGrade(curr), trend);
76 }
77
78 System.out.println("─".repeat(50));
79
80 // Step 6 — Reset marks array for next exam using Arrays.fill()
81 int[] nextExamSlots = Arrays.copyOf(CURRENT_MARKS, count);
82 Arrays.fill(nextExamSlots, 0);
83 System.out.println("\n[6] Next exam slots (reset): "
84 + Arrays.toString(nextExamSlots));
85 }
86}Output:
╔══════════════════════════════════════════╗
║ EXAM RESULT PROCESSING SYSTEM ║
╚══════════════════════════════════════════╝
[1] Results same as previous exam: false
[2] Statistics:
Average: 78.50 | Highest: 95 | Lowest: 55
Students passed: 8/8
[3] Marks in ascending order (for ranking):
[55, 63, 72, 79, 85, 88, 91, 95]
[4] Rank lookup:
Priya Sharma Mark: 85 | Rank: 4
Rohan Mehta Mark: 72 | Rank: 6
Sneha Rao Mark: 91 | Rank: 2
Karan Singh Mark: 63 | Rank: 7
Ananya Iyer Mark: 95 | Rank: 1
Deepak Joshi Mark: 55 | Rank: 8
Meera Nair Mark: 79 | Rank: 5
Suresh Yadav Mark: 88 | Rank: 3
[5] Complete Grade Report:
──────────────────────────────────────────────────
Name Curr Prev Grade
──────────────────────────────────────────────────
Priya Sharma 85 82 A ↑
Rohan Mehta 72 75 B ↓
Sneha Rao 91 91 A+ =
Karan Singh 63 60 B ↑
Ananya Iyer 95 92 A+ ↑
Deepak Joshi 55 55 C =
Meera Nair 79 79 A =
Suresh Yadav 88 88 A =
──────────────────────────────────────────────────
[6] Next exam slots (reset): [0, 0, 0, 0, 0, 0, 0, 0]
All six Arrays methods work together in one real system: equals to detect changes, stream for statistics, copyOf + sort for ranking, binarySearch for position lookup, a full report loop, and fill to reset for the next exam.
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
1int[] unsorted = {72, 45, 91, 38, 88};
2int idx = Arrays.binarySearch(unsorted, 91);
3System.out.println(idx); // undefined result — not guaranteed to be correct
4
5// Fix — sort first
6Arrays.sort(unsorted);
7idx = Arrays.binarySearch(unsorted, 91);
8System.out.println(idx); // correct index in sorted arrayMistake 2 — Using toString() on 2D Arrays
1int[][] matrix = {{1, 2}, {3, 4}};
2System.out.println(Arrays.toString(matrix)); // [[I@7852e922, [I@4554617c] — wrong
3System.out.println(Arrays.deepToString(matrix)); // [[1, 2], [3, 4]] — correctMistake 3 — Forgetting that sort() Modifies the Original
1int[] marks = {85, 72, 91, 63};
2Arrays.sort(marks); // marks is now {63, 72, 85, 91} — original order gone
3
4// If you need the original order (e.g., to map marks to student names):
5int[] copy = Arrays.copyOf(marks, marks.length);
6Arrays.sort(copy); // sort only the copyMistake 4 — Using asList() With Primitive Arrays
1int[] primitiveArr = {1, 2, 3};
2// Arrays.asList(primitiveArr) returns List<int[]> — not List<Integer>!
3java.util.List<int[]> wrong = Arrays.asList(primitiveArr);
4System.out.println(wrong.size()); // 1 — the list has ONE element: the int[] itself
5
6// Fix — use Integer[] instead
7Integer[] boxedArr = {1, 2, 3};
8java.util.List<Integer> correct = Arrays.asList(boxedArr);
9System.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
| Topic | Link |
|---|---|
| How 1D arrays work as the foundation all Arrays methods operate on | Java Arrays → |
| How ArrayList extends array capabilities with dynamic resizing | Java ArrayList → |
| How Collections utility class mirrors Arrays methods for List operations | Java Collections Framework → |
| How streams process arrays functionally with filter, map, and reduce | Java Streams API → |
| How Generics enable type-safe operations on arrays and collections | Java Generics → |