Course topics

By WebNest Studio Engineering Team

Java - Core Tutorial

Java Arrays Class and Copying Arrays

java.util.Arrays is a utility class packed with static helper methods for working with arrays — sorting them, searching them, comparing them, filling them, and copying them — so you rarely need to write these operations by hand. Because arrays themselves expose almost no built-in methods beyond the length field, Arrays fills that gap for everyday array manipulation.

Copying arrays correctly matters because array variables hold references, not the data itself: writing int[] b = a; does not copy anything, it just gives two names to the same underlying array, so changes through either variable are visible through the other. Arrays.copyOf, Arrays.copyOfRange, and System.arraycopy are the standard, correct ways to actually duplicate array data.

Why it matters

Printing, comparing, sorting and copying arrays all behave differently from what newcomers expect: println prints something like [I@1b6d3586, == compares references, and = does not copy. The java.util.Arrays class provides the correct tool for each, and knowing them saves writing loops that the standard library already does well.

Printing and Comparing Arrays

Printing an array directly with System.out.println (or string concatenation) prints an unhelpful internal reference like "[I@1b6d3586", because arrays don't override toString(). Arrays.toString(array) produces a readable "[1, 2, 3]" for one-dimensional arrays, while Arrays.deepToString(array) is required for nested (multidimensional) arrays. Similarly, == on two arrays compares references, not contents, so Arrays.equals(a, b) (or deepEquals for nested arrays) is the correct way to check whether two arrays hold the same elements.

Sorting and Searching

Arrays.sort(array) sorts the array in place in ascending order using a dual-pivot quicksort for primitives (or a stable mergesort variant for objects). Once an array is sorted, Arrays.binarySearch(array, key) finds a value's index efficiently in logarithmic time — but binarySearch gives undefined results on an unsorted array, so sorting first is mandatory.

Copying Arrays

Three standard tools create genuine, independent copies of array data.

  • Arrays.copyOf(array, newLength) — returns a new array of the given length, copying from the start; if newLength is larger, extra slots get default values, and if smaller, the array is truncated.
  • Arrays.copyOfRange(array, from, to) — returns a new array containing elements from index "from" (inclusive) to "to" (exclusive).
  • System.arraycopy(src, srcPos, dest, destPos, length) — the lowest-level, fastest option; it copies into an already-existing destination array rather than creating a new one, and both Arrays.copyOf and copyOfRange actually use it internally.

Time complexity

OperationAverageWorst case
Arrays.sortO(n log n)O(n log n) for objects; O(n²) is possible in theory for primitives
Arrays.binarySearch (sorted array)O(log n)O(log n)
Arrays.copyOf, Arrays.equals, Arrays.toStringO(n)O(n)

Example

Copying, sorting, searching, and slicing an array without mutating the original

Java
import java.util.Arrays;

public class ArraysClassDemo {
    public static void main(String[] args) {
        int[] original = {5, 2, 9, 1, 7};

        int[] copy = Arrays.copyOf(original, original.length);
        Arrays.sort(copy);
        System.out.println("Sorted copy: " + Arrays.toString(copy));
        System.out.println("Original unchanged: " + Arrays.toString(original));

        int index = Arrays.binarySearch(copy, 7);
        System.out.println("Index of 7: " + index);

        int[] partial = Arrays.copyOfRange(original, 1, 4);
        System.out.println("Partial copy: " + Arrays.toString(partial));

        int[] destination = new int[3];
        System.arraycopy(original, 0, destination, 0, 3);
        System.out.println("System.arraycopy result: " + Arrays.toString(destination));
    }
}
Output
Sorted copy: [1, 2, 5, 7, 9]
Original unchanged: [5, 2, 9, 1, 7]
Index of 7: 3
Partial copy: [2, 9, 1]
System.arraycopy result: [5, 2, 9]

Common Mistakes

  • Writing "int[] b = a;" expecting an independent copy — this only copies the reference, so both variables point to the same array.
  • Calling Arrays.binarySearch on an array that was never sorted, which can return an incorrect index with no warning.
  • Using == or .equals() to compare two arrays element-by-element, when only Arrays.equals()/deepEquals() actually compare contents.
  • Printing a multidimensional array with Arrays.toString() instead of Arrays.deepToString(), producing reference strings for the inner arrays instead of their values.

Exercise

Produce a sorted copy of an array while leaving the original untouched, then print both.

Expected output: Original: [5, 3, 9, 1] then Sorted: [1, 3, 5, 9]

Java · starter code
import java.util.Arrays;

public class SortedCopy {
    public static void main(String[] args) {
        int[] original = {5, 3, 9, 1};

        // TODO: create a real copy of original, then sort only the copy

        System.out.println("Original: " + Arrays.toString(original));
        System.out.println("Sorted: " + Arrays.toString(sorted));
    }
}
Show hints
  • int[] sorted = original; does not copy anything — both names would refer to the same array.
  • Arrays.copyOf(original, original.length) creates a new array with the same contents.
Show solution
Java · solution
import java.util.Arrays;

public class SortedCopy {
    public static void main(String[] args) {
        int[] original = {5, 3, 9, 1};

        int[] sorted = Arrays.copyOf(original, original.length);
        Arrays.sort(sorted);

        System.out.println("Original: " + Arrays.toString(original));
        System.out.println("Sorted: " + Arrays.toString(sorted));
    }
}

Quick quiz

1. What does System.out.println(arr) print for an int[]?

  • A. The elements in square brackets
  • B. The elements separated by spaces
  • C. A type code and hash such as [I@1b6d3586
  • D. The length of the array
Show answer

C. Arrays do not override toString(), so you get the type and identity hash. Use Arrays.toString(arr) to print the elements.

2. What must be true of an array before calling Arrays.binarySearch on it?

  • A. It must contain no duplicates
  • B. It must have an even length
  • C. It must hold objects, not primitives
  • D. It must be sorted
Show answer

D. Binary search halves a sorted range at each step. On an unsorted array the result is undefined.

3. After int[] b = a; b[0] = 99;, what is a[0]?

  • A. 99
  • B. Its original value
  • C. 0
  • D. It does not compile
Show answer

A. b = a copies the reference, not the array. Both variables refer to the same array, so the change is visible through a.

Interview questions

What is the difference between a shallow copy and a deep copy of an array?

Show answer

A shallow copy creates a new array but copies the element values as they are. For an array of primitives that is a full copy. For an array of objects, or a 2D array, the new array holds the same references, so both arrays share the underlying objects or rows.

clone(), Arrays.copyOf and System.arraycopy are all shallow. A deep copy has to copy each row or object as well.

How do you compare two arrays for equal content?

Show answer

Use Arrays.equals(a, b), which checks length and compares element by element. a == b and a.equals(b) both compare references, so they are only true when both variables refer to the same array. For nested arrays use Arrays.deepEquals.

Key Points to Remember

  • Assigning one array variable to another copies the reference, not the data — the two variables share the same array.
  • Arrays.copyOf and Arrays.copyOfRange create new arrays; System.arraycopy copies into an existing destination array.
  • Arrays.sort must be called before Arrays.binarySearch, since binary search assumes sorted order.
  • Use Arrays.toString for 1D arrays and Arrays.deepToString for nested/multidimensional arrays when printing.

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs plain Java 17. Frameworks such as Spring, and databases, are not available here. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering