Java Array Operations — Sort, Search, Copy & More
Once you know how to declare and access arrays, the next step is operating on them — sorting, searching, copying, comparing, and converting. Java’s java.util.Arrays utility class handles most of the heavy lifting.
Traversing Arrays
Classic for Loop
int[] nums = {10, 20, 30, 40, 50};
for (int i = 0; i < nums.length; i++) {
System.out.println("Index " + i + " → " + nums[i]);
}
Use this when you need the index.
Enhanced for-each Loop
for (int n : nums) {
System.out.println(n);
}
Cleaner when you only need the value.
Sorting — Arrays.sort()
import java.util.Arrays;
int[] data = {42, 7, 19, 3, 88};
Arrays.sort(data);
System.out.println(Arrays.toString(data));
// [3, 7, 19, 42, 88]
Sort a Sub-range
int[] data = {42, 7, 19, 3, 88};
Arrays.sort(data, 1, 4); // sort index 1 to 3
System.out.println(Arrays.toString(data));
// [42, 3, 7, 19, 88]
Sort Strings
String[] names = {"Charlie", "Alice", "Bob"};
Arrays.sort(names);
// [Alice, Bob, Charlie]
Sort in Reverse Order
import java.util.Collections;
Integer[] nums = {5, 2, 8, 1}; // must use wrapper type
Arrays.sort(nums, Collections.reverseOrder());
// [8, 5, 2, 1]
Performance:
Arrays.sort()uses dual-pivot Quicksort for primitives (O(n log n) average) and TimSort for objects (stable, O(n log n)).
Searching — Arrays.binarySearch()
The array must be sorted before binary search.
int[] sorted = {3, 7, 19, 42, 88};
int index = Arrays.binarySearch(sorted, 19);
System.out.println(index); // 2
int missing = Arrays.binarySearch(sorted, 50);
System.out.println(missing); // negative value (not found)
If the element is not found, the return value is -(insertion point) - 1.
Copying Arrays
Arrays.copyOf()
int[] original = {1, 2, 3, 4, 5};
int[] copy = Arrays.copyOf(original, original.length);
int[] longer = Arrays.copyOf(original, 8); // padded with 0s
// [1, 2, 3, 4, 5, 0, 0, 0]
Arrays.copyOfRange()
int[] slice = Arrays.copyOfRange(original, 1, 4);
// [2, 3, 4]
System.arraycopy()
Low-level and fast:
int[] src = {10, 20, 30, 40, 50};
int[] dest = new int[3];
System.arraycopy(src, 1, dest, 0, 3);
// dest = [20, 30, 40]
clone()
int[] cloned = original.clone();
Note:
clone()andcopyOf()create shallow copies. For arrays of objects, the references are copied — not the objects themselves.
Comparing Arrays — Arrays.equals()
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
System.out.println(a == b); // false (different objects)
System.out.println(Arrays.equals(a, b)); // true (same content)
For 2D arrays, use Arrays.deepEquals():
int[][] grid1 = {{1, 2}, {3, 4}};
int[][] grid2 = {{1, 2}, {3, 4}};
System.out.println(Arrays.deepEquals(grid1, grid2)); // true
Filling Arrays — Arrays.fill()
int[] row = new int[5];
Arrays.fill(row, 42);
// [42, 42, 42, 42, 42]
Arrays.fill(row, 1, 4, 99);
// [42, 99, 99, 99, 42]
Printing Arrays — Arrays.toString()
int[] nums = {10, 20, 30};
System.out.println(nums); // [I@1a2b3c (useless!)
System.out.println(Arrays.toString(nums)); // [10, 20, 30]
For multidimensional arrays:
int[][] matrix = {{1, 2}, {3, 4}};
System.out.println(Arrays.deepToString(matrix));
// [[1, 2], [3, 4]]
Converting Between Arrays and Lists
Array → List
String[] arr = {"A", "B", "C"};
List<String> list = Arrays.asList(arr); // fixed-size list
Warning: The list returned by
Arrays.asList()is fixed-size. You cannotadd()orremove().
For a mutable list:
List<String> mutable = new ArrayList<>(Arrays.asList(arr));
mutable.add("D"); // ✅ works
Java 9+:
List<String> immutable = List.of("A", "B", "C");
List → Array
List<String> list = List.of("X", "Y", "Z");
String[] arr = list.toArray(new String[0]);
Varargs — Variable-Length Arguments
Varargs let a method accept zero or more arguments of the same type. Under the hood, Java creates an array.
public static int sum(int... numbers) {
int total = 0;
for (int n : numbers) {
total += n;
}
return total;
}
sum(); // 0
sum(5); // 5
sum(1, 2, 3); // 6
Rules:
- Only one varargs parameter per method.
- It must be the last parameter.
public static void log(String level, String... messages) {
for (String msg : messages) {
System.out.println("[" + level + "] " + msg);
}
}
Common Mistakes
| Mistake | Why It’s Wrong | Fix |
|---|---|---|
binarySearch() on unsorted array |
Returns wrong results | Sort first |
Modifying Arrays.asList() result |
UnsupportedOperationException |
Wrap in new ArrayList<>() |
Printing array with println(arr) |
Prints hash code | Use Arrays.toString() |
Assuming clone() is deep copy |
Only copies references | Deep-copy manually |
Performance Reference
| Operation | Method | Time Complexity |
|---|---|---|
| Sort (primitives) | Arrays.sort() |
O(n log n) |
| Binary search | Arrays.binarySearch() |
O(log n) |
| Copy | Arrays.copyOf() |
O(n) |
| Fill | Arrays.fill() |
O(n) |
| Compare | Arrays.equals() |
O(n) |
Practice Problems
- Write a method that reverses an array in place.
- Given two sorted arrays, merge them into one sorted array.
- Find the second largest element without sorting.
- Rotate an array to the right by
kpositions.
Key Takeaways
java.util.Arraysprovides static methods for sorting, searching, copying, comparing, and printing.- Always sort before using
binarySearch(). Arrays.asList()returns a fixed-size list — wrap it for mutability.- Use varargs (
int... nums) for flexible method signatures. - Array copies are shallow — beware with object arrays.
What’s Next?
Next up: Multidimensional Arrays — 2D arrays, jagged arrays, and practical examples like tic-tac-toe boards.