Common Array Operations
Explore fundamental array operations in Java using the java.util.Arrays class. Learn how to print arrays properly, initialize values quickly, sort and search efficiently, compare contents deeply, and copy or resize arrays. This lesson helps you write cleaner, faster, and less error-prone code with optimized built-in methods.
We normally use for loops to print array elements, find values, or copy data. While this works for learning the mechanics, writing these loops manually for every task is slow, repetitive, and prone to errors.
Professional Java developers rely on the standard java.util.Arrays class. This utility class is a toolbox containing highly optimized static methods that handle these common operations for us. By using this toolkit, we make our code more readable, faster, and less buggy.
The power of java.util.Arrays
One of the first frustrations beginners face is trying to print an array directly. If we pass an array object to System.out.println(), Java prints its memory reference (technically a type signature and hash code) rather than the actual numbers or strings inside.
To fix this, we use Arrays.toString(). This method converts a simple (one-dimensional) array into a nicely formatted string with brackets and commas. However, if we try this on a multi-dimensional array (like a matrix), Arrays.toString() only prints the memory references of the inner arrays. For nested arrays, we must use Arrays.deepToString(), which recursively formats every layer of data.
Note: We must include import java.util.Arrays; at the top of our file to use these methods.
Line 15: Prints the memory reference (e.g.,
[I@...), which is rarely what we want.Line 18: Prints
[1, 2, 3]clearly.Line 21: Prints
[[A, B], [C, D]]. If we usedtoStringhere, we would see a list of memory addresses.
Rapid initialization with Arrays.fill
Sometimes we need to initialize an array where every slot holds a specific starting value, such as -1 for empty or 0.0 for a baseline calculation. Writing a loop to set every index is unnecessary boilerplate.
Instead, we use Arrays.fill(). This method assigns the specified value to every element in the array instantly.
Line 5: Creates an array of size 5. By default, Java sets these to
0.Line 8: Sets every element in
scoresto-1.Line 10: Prints
[-1, -1, -1, -1, -1].
Sorting arrays
Sorting data allows us to organize information and enables faster searching. Arrays.sort() rearranges the elements of an array into ascending order (e.g., 1 to 10, or A to Z).
It is important to remember that this method is destructive: it modifies the original array directly rather than returning a new sorted copy.
Line 10: Sorts the array. The
numbersvariable now points to the same object, but the internal data is rearranged.Line 12: Prints
[1, 12, 33, 45].
Searching arrays
Once an array is sorted, we can use Arrays.binarySearch() to find an element very quickly. This uses the Binary Search algorithm, which is much faster than checking each element individually.
Rule: The array must be sorted before calling
binarySearch(). If it is not sorted, the result is undefined and unreliable.Return value: If found, it returns the index. If not found, it returns a negative number representing where the element would be if inserted.
Line 8: Searches for
20. Since20is at index 2, it returns2.Line 12: Searches for
99. Since99is not found, it returns a negative number.
Comparing arrays
As we learned with strings and objects, the == operator compares memory references, not content. If we have two distinct array objects containing identical numbers, array1 == array2 returns false.
To check if two arrays contain the same data, we use:
Arrays.equals(a, b): Checks if two flat (1D) arrays have the same length and the same elements in the same order.Arrays.deepEquals(a, b): Checks if two nested (multi-dimensional) arrays contain the same structure and values.
Line 9: Returns
falsebecausea1anda2are different objects in memory.Line 10: Returns
truebecause the contents are identical.Line 17: Returns
false.Arrays.equalssees that the inner array object inm1is different from the inner array object inm2.Line 20: Returns
true.deepEqualstraverses inside the inner arrays to compare the actual string “X”.
Copying and resizing arrays
Arrays in Java have a fixed size. Once created, we cannot make them larger or smaller. If we need a larger array, we must create a new one and copy the elements over. Arrays.copyOf() simplifies this process.
Arrays.copyOf(original, newLength): Creates a new array with the specified length. If the new length is larger, the extra slots are filled with default values (0, null, false).Arrays.copyOfRange(original, from, to): Creates a new array containing a specific slice of the original.
Line 8: Creates a new array of size 5. It copies
10, 20, 30and pads the remaining two slots with0.Line 9: Prints
[10, 20, 30, 0, 0].Line 12: Copies from index 1 up to (but not including) index 3.
Line 14: Prints
[20, 30].
Using java.util.Arrays transforms complex, error-prone loops into single, readable lines of code. Whether we are debugging with deepToString, sorting data for analysis, or resizing storage, these tools are essential for professional Java development.