Skip to content
Home Java Arrays Class in Java

Arrays Class in Java

Where developers are forged. · Structured learning · Free forever.
📍 Part of: Arrays → Topic 5 of 8
Java Arrays class utility methods — Arrays.
⚙️ Intermediate — basic Java knowledge assumed
In this tutorial, you'll learn
Java Arrays class utility methods — Arrays.
  • Arrays.sort() uses dual-pivot Quicksort for primitives (O(n log n)) and Timsort for objects.
  • binarySearch() only works correctly on a sorted array — always sort first.
  • copyOf() creates a new array; changes to the copy do not affect the original.
✦ Plain-English analogy ✦ Real code with output ✦ Interview questions
Quick Answer

java.util.Arrays provides static utility methods for arrays: sort() for O(n log n) sorting, binarySearch() for O(log n) search on sorted arrays, copyOf() for copying, fill() for initialisation, stream() for functional operations, and asList() to get a fixed-size List view.

Sorting Arrays

Example · JAVA
12345678910111213141516171819202122232425
package io.thecodeforge.java.arrays;

import java.util.Arrays;

public class ArraysSortDemo {
    public static void main(String[] args) {
        int[] numbers = {5, 2, 8, 1, 9, 3};
        Arrays.sort(numbers);
        System.out.println(Arrays.toString(numbers)); // [1, 2, 3, 5, 8, 9]

        // Sort a range (from index 1 to 4, exclusive end)
        int[] partial = {5, 2, 8, 1, 9, 3};
        Arrays.sort(partial, 1, 4);  // sorts indices 1,2,3 only
        System.out.println(Arrays.toString(partial)); // [5, 1, 2, 8, 9, 3]

        // Sort objects — natural order (Comparable)
        String[] words = {"banana", "apple", "cherry", "date"};
        Arrays.sort(words);
        System.out.println(Arrays.toString(words));   // [apple, banana, cherry, date]

        // Sort objects — custom Comparator (by length)
        Arrays.sort(words, (a, b) -> a.length() - b.length());
        System.out.println(Arrays.toString(words));   // [date, apple, banana, cherry]
    }
}
▶ Output
[1, 2, 3, 5, 8, 9]
[5, 1, 2, 8, 9, 3]
[apple, banana, cherry, date]
[date, apple, banana, cherry]

Searching, Copying, and Filling

Example · JAVA
1234567891011121314151617181920212223242526272829303132333435
package io.thecodeforge.java.arrays;

import java.util.Arrays;

public class ArraysUtilities {
    public static void main(String[] args) {
        int[] sorted = {1, 3, 5, 7, 9, 11};

        // binarySearch — MUST be sorted first
        System.out.println(Arrays.binarySearch(sorted, 7));  // 3 (index)
        System.out.println(Arrays.binarySearch(sorted, 4));  // negative = not found

        // copyOf — new array, truncates or pads with zeros
        int[] copy = Arrays.copyOf(sorted, 4);
        System.out.println(Arrays.toString(copy));   // [1, 3, 5, 7]

        int[] extended = Arrays.copyOf(sorted, 8);
        System.out.println(Arrays.toString(extended)); // [1, 3, 5, 7, 9, 11, 0, 0]

        // copyOfRange — copy a slice
        int[] slice = Arrays.copyOfRange(sorted, 2, 5);
        System.out.println(Arrays.toString(slice));  // [5, 7, 9]

        // fill — initialise all elements
        int[] grid = new int[5];
        Arrays.fill(grid, -1);
        System.out.println(Arrays.toString(grid));   // [-1, -1, -1, -1, -1]

        // equals and deepEquals
        int[] a = {1, 2, 3};
        int[] b = {1, 2, 3};
        System.out.println(a == b);           // false — different references
        System.out.println(Arrays.equals(a, b)); // true  — element comparison
    }
}
▶ Output
3
-3
[1, 3, 5, 7]
[1, 3, 5, 7, 9, 11, 0, 0]
[5, 7, 9]
[-1, -1, -1, -1, -1]
false
true

Arrays.stream and Arrays.asList

Example · JAVA
1234567891011121314151617181920212223242526272829303132
package io.thecodeforge.java.arrays;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class ArraysStreamDemo {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

        // Arrays.stream — IntStream for primitives
        int sum = Arrays.stream(numbers).sum();
        System.out.println("Sum: " + sum);  // 55

        double avg = Arrays.stream(numbers).average().orElse(0);
        System.out.println("Avg: " + avg);  // 5.5

        int[] evens = Arrays.stream(numbers)
                           .filter(n -> n % 2 == 0)
                           .toArray();
        System.out.println(Arrays.toString(evens));  // [2, 4, 6, 8, 10]

        // Arrays.asList — fixed-size List view (add/remove throw UnsupportedOperationException)
        String[] arr = {"a", "b", "c"};
        List<String> list = Arrays.asList(arr);
        list.set(0, "x");  // set works — modifies underlying array
        System.out.println(Arrays.toString(arr));  // [x, b, c]
        // list.add("d");  // throws UnsupportedOperationException

        // For a mutable list, wrap: new ArrayList<>(Arrays.asList(arr))
    }
}
▶ Output
Sum: 55
Avg: 5.5
[2, 4, 6, 8, 10]
[x, b, c]

🎯 Key Takeaways

  • Arrays.sort() uses dual-pivot Quicksort for primitives (O(n log n)) and Timsort for objects.
  • binarySearch() only works correctly on a sorted array — always sort first.
  • copyOf() creates a new array; changes to the copy do not affect the original.
  • Arrays.asList() returns a fixed-size view — you cannot add or remove elements.
  • Arrays.equals() compares element by element; == compares array references.

Interview Questions on This Topic

  • QWhat is the difference between Arrays.equals() and == for arrays?
  • QWhy does Arrays.asList() not support the add() method?
  • QWhat does Arrays.binarySearch() return when the element is not in the array?

Frequently Asked Questions

Why does Arrays.asList() not support add() or remove()?

Arrays.asList() returns a fixed-size list backed by the array. The array has a fixed size, so the list cannot grow or shrink. set() works because it replaces elements in place. Wrap with new ArrayList<>(Arrays.asList(arr)) to get a fully mutable list.

What does binarySearch() return when the element is not found?

It returns -(insertion_point) - 1, where insertion_point is the index where the element would be inserted to keep the array sorted. For example, searching for 4 in [1, 3, 5, 7] returns -3 (insertion point is 2, so -(2)-1 = -3). This lets you derive the insertion point from the negative result.

🔥
Naren Founder & Author

Developer and founder of TheCodeForge. I built this site because I was tired of tutorials that explain what to type without explaining why it works. Every article here is written to make concepts actually click.

← PreviousArray Searching in JavaNext →Jagged Arrays in Java
Forged with 🔥 at TheCodeForge.io — Where Developers Are Forged