bhylu.com

Advertisements

Java Arrays API Reference

Arrays provides operations on array contents, while length belongs to the array object itself. Read mutation and ordering requirements before choosing a helper.

Understand the idea

There are separate overloads for primitive and object arrays. A shallow object-array comparison does not recursively compare nested arrays; deepEquals addresses a different shape. Sorting and filling mutate the supplied array, while copying returns another container. A view created by Arrays.asList has a fixed size backed by the object array and is not a growable ArrayList.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] original = {5, 2, 8};
        int[] copy = Arrays.copyOf(original, original.length);
        Arrays.sort(copy);
        System.out.println(Arrays.equals(original, copy));
        System.out.println(Arrays.binarySearch(copy, 5));
    }
}

Expected output

false
1

The sorted copy has a different sequence from the original, so equality is false. Binary search is valid because the copy is sorted under a compatible order. The source remains available in arrival order. For nested arrays, choose a comparison that matches whether the elements themselves are arrays.

Contracts to look up

API or language termWhat to check
array.lengthA fixed-size field, not a length() method.
Arrays.compareLexicographic array comparison with overload-specific element rules.
Arrays.equals, Arrays.deepEqualsElement comparison versus nested-array-aware comparison.
Arrays.sort, Arrays.parallelSortMutate the target range or array into a compatible order.
Arrays.fillAssign the supplied value into all elements or a half-open range.
Arrays.copyOf, Arrays.copyOfRangeCreate another array container; referenced element objects are not deeply cloned.
Arrays.binarySearchRequires compatible sorted input; a negative result encodes an insertion point.
Arrays.asListReturns a fixed-size backed object-array view.
Arrays.toString, Arrays.deepToStringReadable diagnostics, with a nested-array-aware form.

Check the official Java documentation for detailed contracts and supported options.

Advertisements