Java
Module 5: Java ArraysBeginner22 min read

Arrays Utility Class, Reversal & Interview Problems

Solve classic array problems including two-pointer reversal, binary search, and finding maximum/second-largest elements.

Key Takeaways & Core Concepts
  • Arrays.sort(arr) / Arrays.parallelSort(arr): Sorts arrays in-place.
  • Arrays.binarySearch(arr, key): O(log n) search (the array must be sorted first, otherwise the result is undefined!).
  • Arrays.copyOf(arr, newLength) & Arrays.copyOfRange(arr, from, to): Fast native array copying.
  • Arrays.equals(a, b): Deeply compares contents (whereas a.equals(b) only compares references!).

`java.util.Arrays` Essentials

The Arrays utility class provides battle-tested static algorithms:

  • Arrays.sort(arr) / Arrays.parallelSort(arr): Sorts arrays in-place.
  • Arrays.binarySearch(arr, key): O(log n) search (the array must be sorted first, otherwise the result is undefined!).
  • Arrays.copyOf(arr, newLength) & Arrays.copyOfRange(arr, from, to): Fast native array copying.
  • Arrays.equals(a, b): Deeply compares contents (whereas a.equals(b) only compares references!).
In-Place Array Reversal & Binary Search
1import java.util.Arrays;
2
3public class Main {
4 static void reverse(int[] arr) {
5 int l = 0, r = arr.length - 1;
6 while (l < r) {
7 int tmp = arr[l];
8 arr[l++] = arr[r];
9 arr[r--] = tmp;
10 }
11 }
12
13 public static void main(String[] args) {
14 int[] data = {10, 20, 30, 40, 50};
15 System.out.println("Index of 30: " + Arrays.binarySearch(data, 30));
16 reverse(data);
17 System.out.println("Reversed: " + Arrays.toString(data));
18 }
19}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
19 lines
Note: `Arrays.binarySearch` returns the 0-based index if found, or a negative insertion point if absent.

Classic Interview Pattern: Two Pointers

Reversing an array in-place, partitioning zeroes, or finding pairs in a sorted array uses left = 0 and right = arr.length - 1, running in O(n) time and O(1) extra space.

Practice & AssessmentJava Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)