Search⌘ K
AI Features

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.

Java 25
import java.util.Arrays;
public class ArrayPrinting {
public static void main(String[] args) {
// A simple 1D array
int[] numbers = {1, 2, 3};
// A 2D array (matrix)
String[][] matrix = {
{"A", "B"},
{"C", "D"}
};
// 1. Trying to print directly (Unhelpful output)
System.out.println("Direct Print: " + numbers);
// 2. Using Arrays.toString() for 1D arrays
System.out.println("Arrays.toString: " + Arrays.toString(numbers));
// 3. Using Arrays.deepToString() for 2D arrays
System.out.println("Arrays.deepToString: " + Arrays.deepToString(matrix));
}
}
  • 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 used toString here, 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.

Java 25
import java.util.Arrays;
public class ArrayFill {
public static void main(String[] args) {
int[] scores = new int[5];
// Fill the entire array with -1 (representing "no score yet")
Arrays.fill(scores, -1);
System.out.println(Arrays.toString(scores));
}
}
  • Line 5: Creates an array of size 5. By default, Java sets these to 0.

  • Line 8: Sets every element in scores to -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.

Java 25
import java.util.Arrays;
public class ArraySorting {
public static void main(String[] args) {
int[] numbers = {45, 12, 1, 33};
System.out.println("Before: " + Arrays.toString(numbers));
// Sorts the array in place
Arrays.sort(numbers);
System.out.println("After: " + Arrays.toString(numbers));
}
}
  • Line 10: Sorts the array. The numbers variable 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.

Java 25
import java.util.Arrays;
public class ArraySearching {
public static void main(String[] args) {
int[] lottoNumbers = {1, 12, 20, 33, 45}; // Must be sorted first
// 1. Search for an existing value (20)
int indexFound = Arrays.binarySearch(lottoNumbers, 20);
System.out.println("Found 20 at index: " + indexFound);
// 2. Search for a missing value (99)
int indexMissing = Arrays.binarySearch(lottoNumbers, 99);
System.out.println("Result for 99: " + indexMissing);
}
}
  • Line 8: Searches for 20. Since 20 is at index 2, it returns 2.

  • Line 12: Searches for 99. Since 99 is 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:

  1. Arrays.equals(a, b): Checks if two flat (1D) arrays have the same length and the same elements in the same order.

  2. Arrays.deepEquals(a, b): Checks if two nested (multi-dimensional) arrays contain the same structure and values.

Java 25
import java.util.Arrays;
public class ArrayComparison {
public static void main(String[] args) {
int[] a1 = {1, 2, 3};
int[] a2 = {1, 2, 3};
// 1D Comparison
System.out.println("Using ==: " + (a1 == a2));
System.out.println("Using equals: " + Arrays.equals(a1, a2));
String[][] m1 = { {"X"} };
String[][] m2 = { {"X"} };
// Multi-dimensional Comparison
// Arrays.equals fails here because it only checks the inner array references
System.out.println("Matrix equals: " + Arrays.equals(m1, m2));
// Arrays.deepEquals checks the actual strings inside
System.out.println("Matrix deepEquals: " + Arrays.deepEquals(m1, m2));
}
}
  • Line 9: Returns false because a1 and a2 are different objects in memory.

  • Line 10: Returns true because the contents are identical.

  • Line 17: Returns false. Arrays.equals sees that the inner array object in m1 is different from the inner array object in m2.

  • Line 20: Returns true. deepEquals traverses 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.

Java 25
import java.util.Arrays;
public class ArrayCopying {
public static void main(String[] args) {
int[] original = {10, 20, 30};
// 1. Resizing: Make a bigger copy
int[] expanded = Arrays.copyOf(original, 5);
System.out.println("Expanded: " + Arrays.toString(expanded));
// 2. Slicing: Take elements from index 1 (inclusive) to 3 (exclusive)
int[] slice = Arrays.copyOfRange(original, 1, 3);
System.out.println("Sliced: " + Arrays.toString(slice));
}
}
  • Line 8: Creates a new array of size 5. It copies 10, 20, 30 and pads the remaining two slots with 0.

  • 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.