Skip to main content
Advertisement

5.4 Arrays Utility Class

When handling arrays in Java, developers do not need to manually write iteration loops (for) constantly to print or sort them. Java natively provides the highly optimized java.util.Arrays class to support robust copying, sorting, and printing of arrays effortlessly.

1. Array Output (Arrays.toString)

If you attempt to directly print an array's reference variable, a meaningless JVM explicit memory address (like [I@1b6d3586) will be outputted. To view the actual array values cleanly formatted as a string without manual for loop iterations, simply use Arrays.toString().

import java.util.Arrays; // (1) Utility Class import is mandatory

public class ArraysEx {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
System.out.println(Arrays.toString(arr));
// Output: [10, 20, 30, 40, 50]
}
}

(For multi-dimensional nested arrays, use Arrays.deepToString() instead).

2. Array Copying (Arrays.copyOf)

Because arrays cannot change their fixed lengths after declaration, if you require a larger array, you must create a new one and copy the existing elements. The Arrays.copyOf() method executes this natively and quickly.

int[] arr = {1, 2, 3};
int[] arr2 = Arrays.copyOf(arr, arr.length); // Clone the exact same array
int[] arr3 = Arrays.copyOf(arr, 5); // Copy into a size 5 array. Fills extra spaces with 0.
int[] arr4 = Arrays.copyOfRange(arr, 1, 3); // Copy elements from index 1 to 2.

3. Array Sorting (Arrays.sort)

To easily sort array elements in ascending order, invoking Arrays.sort() is all you need. Java's optimized algorithm handles it efficiently.

int[] scores = { 95, 75, 80, 100, 50 };
Arrays.sort(scores);
System.out.println(Arrays.toString(scores));
// Output: [50, 75, 80, 95, 100]

4. Array Comparison (Arrays.equals)

Used to precisely verify whether two separate arrays have the exact same contents. Using the == operator will only compare their JVM memory addresses, so you must use Arrays.equals() for safety.

int[] a = {1, 2, 3};
int[] b = {1, 2, 3};

System.out.println(a == b); // false (Different memory addresses)
System.out.println(Arrays.equals(a, b)); // true (Contents inside match perfectly)
Advertisement