Java Array Sorting, Copying & java.util.Arrays Masterclass

โ˜• Java 21+ LTS ๐ŸŸข Chapter 30 of 47 ๐Ÿ“‚ Phase 7: Arrays & Matrices ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this chapter:

In-Place Array Reversal ยท Bubble Sort Algorithm ยท Arrays.sort() Internals (Dual-Pivot Quicksort) ยท 4 Array Copying Techniques ยท System.arraycopy() vs Arrays.copyOf() ยท Shallow vs Deep Copy ยท Arrays.fill(), Arrays.equals(), Arrays.mismatch()

Mastering sorting algorithms, memory duplication techniques, and the complete java.util.Arrays utility library: two-pointer in-place reversal, step-by-step Bubble Sort mechanics, JVM Dual-Pivot Quicksort architecture, high-speed memory copying with System.arraycopy(), and deep equality inspections.

1. In-Place Array Reversal (Two-Pointer Algorithm)

Reversing an array without creating a second array saves heap allocation:

int left = 0, right = arr.length - 1;
while (left < right) {
    int temp = arr[left];
    arr[left] = arr[right];
    arr[right] = temp;
    left++;
    right--;
}
- Runs in $O(N/2) = O(N)$ time. - Uses $O(1)$ auxiliary space.

2. Understanding Bubble Sort Mechanics

Bubble Sort repeatedly compares adjacent elements and swaps them if they are in the wrong order. With each outer pass, the largest remaining element "bubbles up" to its final position at the end of the array:

Pass 1: [5, 1, 4, 2, 8] -> [1, 5, 4, 2, 8] -> [1, 4, 5, 2, 8] -> [1, 4, 2, 5, 8] (8 is in place)
  Pass 2: [1, 4, 2, 5, 8] -> [1, 2, 4, 5, 8] (5 is in place)
  Pass 3: Array is sorted!

- Time Complexity: $O(N^2)$ worst/average case; $O(N)$ best case when optimized with a swapped boolean flag.

3. 4 Ways to Copy Arrays in Java

In Java, writing int[] copy = original; does NOT copy the array! It simply creates a second reference pointing to the exact same Heap object. Modifying copy[0] will corrupt original[0]!

To duplicate the array data, use one of these 4 techniques:

Method Syntax Characteristics
1. Manual Loop for (int i=0; i<len; i++) copy[i] = orig[i]; Simple, readable, manual control.
2. System.arraycopy() System.arraycopy(src, 0, dest, 0, len); Fastest (Native C++ JVM memmove call directly in RAM).
3. Arrays.copyOf() int[] copy = Arrays.copyOf(orig, newLength); Allocates and copies in one concise call; allows resizing.
4. clone() int[] copy = orig.clone(); Creates a shallow clone of the array object.

4. The java.util.Arrays Utility Toolkit

The java.util.Arrays class contains static helper methods:

- Arrays.toString(arr): Converts 1D array into clean readable string "[1, 2, 3]".
- Arrays.sort(arr): In-place ascending sort.
- Arrays.fill(arr, val): Sets every slot in the array to val.
- Arrays.equals(arr1, arr2): Checks if two 1D arrays contain identical elements in identical order.
- Arrays.mismatch(arr1, arr2): (Java 9+) Returns the index of the first differing element, or -1 if identical.
- Arrays.compare(arr1, arr2): (Java 9+) Lexicographical array comparison.

Beginner Example & Code Anatomy

โ˜• Main.java โ€” Chapter 30 Core Example
import java.util.Arrays;

public class Main {
    // Bubble sort with optimized early exit
    public static void bubbleSort(int[] arr) {
        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
            boolean swapped = false;
            for (int j = 0; j < n - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    swapped = true;
                }
            }
            if (!swapped) break; // Array is already sorted
        }
    }

    // In-place two-pointer reversal
    public static void reverseArray(int[] arr) {
        int left = 0, right = arr.length - 1;
        while (left < right) {
            int temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            left++;
            right--;
        }
    }

    public static void main(String[] args) {
        System.out.println("=== 1. In-Place Array Reversal ===");
        int[] numbers = {10, 20, 30, 40, 50};
        System.out.println("Original              : " + Arrays.toString(numbers));
        reverseArray(numbers);
        System.out.println("Reversed              : " + Arrays.toString(numbers));

        System.out.println("
=== 2. Custom Bubble Sort ===");
        int[] unsorted = {64, 34, 25, 12, 22, 11, 90};
        System.out.println("Before Bubble Sort    : " + Arrays.toString(unsorted));
        bubbleSort(unsorted);
        System.out.println("After Bubble Sort     : " + Arrays.toString(unsorted));

        System.out.println("
=== 3. Array Copying Techniques ===");
        int[] original = {100, 200, 300, 400};

        // Technique A: Arrays.copyOf()
        int[] copyA = Arrays.copyOf(original, original.length);

        // Technique B: System.arraycopy()
        int[] copyB = new int[original.length];
        System.arraycopy(original, 0, copyB, 0, original.length);

        // Technique C: clone()
        int[] copyC = original.clone();

        System.out.println("Copy via Arrays.copyOf: " + Arrays.toString(copyA));
        System.out.println("Copy via arraycopy()  : " + Arrays.toString(copyB));
        System.out.println("Copy via clone()      : " + Arrays.toString(copyC));

        System.out.println("
=== 4. Arrays Utility Class Methods ===");
        System.out.println("Arrays.equals(A, B)   : " + Arrays.equals(copyA, copyB)); // true

        int[] fillArray = new int[5];
        Arrays.fill(fillArray, 7);
        System.out.println("Arrays.fill(..., 7)   : " + Arrays.toString(fillArray));

        int[] rangeCopy = Arrays.copyOfRange(original, 1, 3); // Extracts [200, 300]
        System.out.println("Arrays.copyOfRange(1,3): " + Arrays.toString(rangeCopy));
    }
}
๐Ÿ’ป Program Console Output
=== 1. In-Place Array Reversal === Original : [10, 20, 30, 40, 50] Reversed : [50, 40, 30, 20, 10] === 2. Custom Bubble Sort === Before Bubble Sort : [64, 34, 25, 12, 22, 11, 90] After Bubble Sort : [11, 12, 22, 25, 34, 64, 90] === 3. Array Copying Techniques === Copy via Arrays.copyOf: [100, 200, 300, 400] Copy via arraycopy() : [100, 200, 300, 400] Copy via clone() : [100, 200, 300, 400] === 4. Arrays Utility Class Methods === Arrays.equals(A, B) : true Arrays.fill(..., 7) : [7, 7, 7, 7, 7] Arrays.copyOfRange(1,3): [200, 300]

๐Ÿ” Line-by-Line Code Explanation

reverseArray(numbers);

Reverses the array elements directly in place using two converging pointers without allocating a new array.

System.arraycopy(original, 0, copyB, 0, original.length);

Executes high-speed native memory copying directly in the JVM with zero bytecode overhead.

Arrays.copyOf(original, original.length);

Allocates a new heap array and copies elements in a single expression.

Arrays.fill(fillArray, 7);

Assigns value 7 to every element in the array.

Arrays.equals(copyA, copyB);

Compares content element-by-element, returning true if lengths and corresponding elements match.

Practical Real-World Example

โ˜• PracticalApplication.java โ€” Industry Implementation
public class PracticalApplication {
    public static void main(String[] args) {
        // Industry Simulation: Dynamic Array Expansion & Buffer Management
        int[] buffer = {10, 20, 30};
        System.out.println("Initial Buffer (Cap 3): " + Arrays.toString(buffer));

        // Incoming new data exceeds capacity: Expand buffer to 2x capacity
        int[] expandedBuffer = Arrays.copyOf(buffer, buffer.length * 2);
        expandedBuffer[3] = 40;
        expandedBuffer[4] = 50;

        System.out.println("Expanded Buffer(Cap 6): " + Arrays.toString(expandedBuffer));
    }
}
๐Ÿ’ป Practical Console Output
Initial Buffer (Cap 3): [10, 20, 30] Expanded Buffer(Cap 6): [10, 20, 30, 40, 50, 0]
โš ๏ธ Common Mistakes & Professional Best Practices
  • Writing int[] b = a; believing it clones the array. It only creates a second reference to the same array object.
  • Calling a.equals(b) on two arrays instead of Arrays.equals(a, b). a.equals(b) compares memory addresses!
  • Printing an array with System.out.println(arr) which prints memory hashes like [I@1b6d3586 instead of Arrays.toString(arr).
  • Forgetting that Arrays.copyOfRange(arr, 1, 4) uses half-open range [1, 4) and excludes index 4.
๐ŸŽฏ Hands-on Coding Challenge

Test your understanding by writing the code directly in your editor or running in our online Java compiler:

โ˜• Challenge.java
// Coding Challenge:
// Write a method removeDuplicates(int[] sortedArr) that:
// 1. Takes a SORTED array with duplicate numbers: {1, 1, 2, 2, 3, 4, 4, 5}.
// 2. Removes duplicates in-place in O(N) time and returns the new unique count.

public class Challenge {
    public static int removeDuplicates(int[] arr) {
        if (arr.length == 0) return 0;
        int uniqueIdx = 0;
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] != arr[uniqueIdx]) {
                uniqueIdx++;
                arr[uniqueIdx] = arr[i];
            }
        }
        return uniqueIdx + 1;
    }

    public static void main(String[] args) {
        int[] sorted = {1, 1, 2, 2, 3, 4, 4, 5};
        int newLength = removeDuplicates(sorted);
        System.out.println("Unique Count : " + newLength);
        System.out.print("Unique Array : ");
        for (int i = 0; i < newLength; i++) {
            System.out.print(sorted[i] + " ");
        }
        System.out.println();
    }
}

๐Ÿ’ก Frequently Asked Questions & Interview Insights

โ“ Why does System.out.println(new int[]{1,2,3}) print [I@6d06d69c?

Arrays in Java inherit `toString()` from `java.lang.Object`, which prints the class name (`[I` means 1D integer array) followed by `@` and the hexadecimal unsigned hash code. Always use `Arrays.toString(arr)` to print values.

โ“ What sorting algorithm does Arrays.sort() use for primitives vs objects?

For primitives (`int[]`, `double[]`), it uses **Dual-Pivot Quicksort** by Vladimir Yaroslavskiy (fast, $O(N \log N)$, not stable). For objects (`String[]`, `Comparable[]`), it uses **Timsort** (stable, derived from merge sort).

โ“ Which array copy method is the fastest in Java?

`System.arraycopy()` is the fastest because it is a native C/C++ method that translates directly into high-speed SIMD memory block copies in CPU hardware.

๐Ÿš€ Quick Chapter Recap

  • Two-pointer algorithms reverse arrays in $O(N)$ time with zero additional memory allocation.
  • Assigning int[] b = a; copies references, not data; use Arrays.copyOf() or System.arraycopy() for true cloning.
  • Always use Arrays.toString() to print arrays and Arrays.equals() to compare array contents.
  • Arrays.sort() uses Dual-Pivot Quicksort for primitives and Timsort for objects.
  • System.arraycopy() is the industry standard for high-performance memory duplication.
โ† Prev: 29. Array Math & Search Algorithms Next: 31. 2D & Jagged Arrays โ†’
OC
Curated by Our Compiler Java Technical Editorial Team
Published for 2026 Academic & Enterprise Reference ยท 100% Free & Open Access