Java Array Operations and Sorting

Java's Arrays utilities support copying, searching and sorting arrays.

Lesson 33 of 127Intermediate14 min read

Java's Arrays utilities support copying, searching and sorting arrays. The important details are whether an operation mutates its argument, what ordering a search expects and how ranges are bounded. These examples make each result visible instead of treating every utility as an interchangeable shortcut.

Review the related foundation lesson when you need a prerequisite. The complete programs below use Java 17-compatible syntax.

Sorting in place

Arrays.sort orders an array in place. Primitive arrays use numeric ordering, while object arrays can use natural order or a supplied comparator.

Arrays.sort changes the supplied array in place. Numeric primitive arrays use ascending numeric order. Object arrays use natural ordering or a supplied Comparator. A range sort accepts a start index inclusive and an end index exclusive, so sorting from one to four changes positions one, two and three. Sorting is not a new-array operation; clone first when the original order matters.

Copying and equality

Arrays.copyOf creates a new array. Arrays.equals compares corresponding array values, while == checks whether two references identify the same array.

Arrays.copyOf creates a new array and copies the available elements. A longer copy fills remaining primitive slots with defaults, such as zero, or reference slots with null. A shorter copy truncates the copied sequence. For object arrays, copied elements are shared references rather than cloned objects. copyOfRange also uses an exclusive upper bound, a convention shared by many Java range APIs.

Binary-search prerequisites

Arrays.binarySearch requires the array to be sorted under the same ordering. A negative result encodes an insertion point rather than simply always returning minus one.

Arrays.binarySearch requires data sorted according to the same order used for searching. A nonnegative result identifies one matching index, not necessarily the first duplicate. A negative result encodes the insertion point as minus insertion point minus one. Do not treat every negative number as an arbitrary failure code if you need to calculate where an absent value belongs.

Displaying arrays, equality and backed views

Arrays.toString formats a one-dimensional array; deepToString helps with nested arrays. A readable display is different from a durable serialization format.

Arrays.equals compares corresponding elements of ordinary arrays, while == compares the array objects themselves. For nested arrays, deepEquals is available for recursive element comparison, and deepToString provides readable nested output. Arrays.asList creates a fixed-size list backed by an object array; replacing an element can update that array, but adding or removing elements is unsupported.

Running the examples

Save name.java, compile it with javac --release 17 name.java, and run java name. Use each program's own public class name and filename.

How SortedTimes produces its output

copyOf creates a separate int array before sorting. sort rearranges that copy to 24, 26, 29, 31, while times retains its original order. toString prints the sorted elements, then binarySearch looks for twenty-nine in that sorted sequence and returns index two. The index refers to sorted, so it is not the original index of twenty-nine in times.

How ArraySorting produces its output

The clone saves an independent primitive array before sorting. Arrays.sort rearranges scores into ascending order, while original retains its initial sequence. Because the elements are primitive ints, this copy is enough to separate their stored values. A copy of an object array would still share the referenced objects.

How ArraySearchResult produces its output

Seven is absent but would belong at index two, before nine. binarySearch encodes that insertion point as minus two minus one, producing minus three. Decoding with -result - 1 restores two. The sorted input makes this interpretation valid; searching the unsorted sequence would not provide the promised result.

Do not confuse a view with a resizable list

Arrays.asList on an object array returns a fixed-size list backed by that array. Calling set can replace an element and is reflected in the array, while add and remove cannot change its size. Wrapping it in new ArrayList creates a separately resizable collection structure. For a primitive int array, Arrays.asList receives the entire array as one element rather than boxing every integer into separate entries. Use explicit conversion when you need List<Integer>. These distinctions matter when a utility's return type says List but does not promise that every structural operation is supported.

Copying into an existing destination

System.arraycopy copies a chosen range into an existing array instead of allocating the destination for you. Its source position, destination position and count are separate arguments. Both ranges must fit their arrays, and incompatible reference element types can cause ArrayStoreException. It supports overlapping copies within the same array, so shifting a block does not require a hand-written loop whose direction may overwrite unread values. Primitive array element types must match appropriately; it does not convert an int array into a long array. Use Arrays.copyOf when allocating a resized copy is the actual goal, and arraycopy when a specific destination already exists.

Java Summary

  • Arrays.sort orders an array in place. Primitive arrays use numeric ordering, while object arrays can use natural order or a supplied comparator.
  • Arrays.copyOf creates a new array. Arrays.equals compares corresponding array values, while == checks whether two references identify the same array.
  • Arrays.binarySearch requires the array to be sorted under the same ordering. A negative result encodes an insertion point rather than simply always returning minus one.
  • Arrays.toString formats a one-dimensional array; deepToString helps with nested arrays. A readable display is different from a durable serialization format.
  • Continue with Java exercises, Java quizzes and the Java study roadmap.

Java Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Java Array Operations and Sorting in a complete program

Java
public class SortedTimes  {
    public static void main(String[] args)  {
        int[] times =  {
            29, 24, 31, 26
        };
        int[] sorted = java.util.Arrays.copyOf(times, times.length);
        java.util.Arrays.sort(sorted);
        System.out.println(java.util.Arrays.toString(sorted));
        System.out.println(java.util.Arrays.binarySearch(sorted, 29));
    }
}
Output
[24, 26, 29, 31]
2
Line-by-line explanation
  1. Line 8Evaluates java.util.Arrays.toString(sorted) and prints [24, 26, 29, 31].
  2. Line 9Evaluates java.util.Arrays.binarySearch(sorted, 29) and prints 2.
Example 2

Sorting mutates the supplied array

Java
public class ArraySorting  {
    public static void main(String[] args)  {
        int[] scores =  {
            8, 2, 5
        };
        int[] original = scores.clone();
        java.util.Arrays.sort(scores);
        System.out.println(java.util.Arrays.toString(scores));
        System.out.println(java.util.Arrays.toString(original));
    }
}
Output
[2, 5, 8]
[8, 2, 5]
Line-by-line explanation
  1. Line 8Evaluates java.util.Arrays.toString(scores) and prints [2, 5, 8].
  2. Line 9Evaluates java.util.Arrays.toString(original) and prints [8, 2, 5].
Example 3

Absent search results encode insertion points

Java
public class ArraySearchResult  {
    public static void main(String[] args)  {
        int[] values =  {
            2, 5, 9
        };
        int result = java.util.Arrays.binarySearch(values, 7);
        System.out.println(result);
        System.out.println(-result - 1);
    }
}
Output
-3
2
Line-by-line explanation
  1. Line 7Evaluates result and prints -3.
  2. Line 8Evaluates -result - 1 and prints 2.

Java FAQ

Why does printing an array directly look unusual?

Most arrays do not override Object.toString with element formatting. Use Arrays.toString for a one-dimensional array and Arrays.deepToString for nested arrays. This changes the display, not the array contents or the equality rules.

Can binarySearch find the first duplicate reliably?

No. When equal elements exist, the API does not promise which matching index it returns. Use an explicit lower-bound search if the first occurrence matters, and document the same ordering assumptions used to sort the data.

Is Arrays.sort stable?

For arrays of objects, yes: equal elements keep their original order, which matters when sorting by one field after another. For primitive arrays, stability doesn't apply, because two equal numbers can't be told apart.

How do I sort only part of an array?

Pass a start index and an end index: Arrays.sort(a, 1, 4) sorts positions 1, 2 and 3 and leaves the rest alone. As with substring, the start is included and the end is excluded.

What is the difference between Arrays.copyOf and clone()?

clone() always makes a copy with the same length. Arrays.copyOf(a, n) lets you choose the new length, truncating or padding with default values, and Arrays.copyOfRange copies a slice. All three are shallow copies, so object elements are shared.

Java Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choiceeasy

Which operation preserves an int array's original order before sorting?

Multiple choicemedium

What must be true before binarySearch?

Java Quiz

2 questions to check what you learned.

  1. What does Arrays.equals compare?

    • Corresponding element values
    • Only reference identity
    • Only array lengths
  2. Which positions does sort(array, 1, 4) include?

    • 1, 2 and 3
    • 1, 2, 3 and 4
    • Only 4