Of course! Let's dive deep into java.util.Arrays.sort(). This is a fundamental and highly useful method in Java for sorting arrays.

The Basics: What is Arrays.sort()?
Arrays.sort() is a static utility method in the java.util.Arrays class. It is used to sort the elements of an array into ascending order. It's a convenient, one-line way to sort any primitive or object array.
Key Characteristics:
- Static Method: You call it directly on the
Arraysclass (e.g.,Arrays.sort(myArray)), not on an array instance. - In-place Sort: It modifies the original array. It does not return a new, sorted array.
- Overloaded: The method is overloaded to handle different types of arrays:
- Primitive arrays (
int[],double[],char[], etc.) - Object arrays (
String[],Integer[],YourCustomObject[], etc.)
- Primitive arrays (
How to Use It (with Examples)
A. Sorting Primitive Arrays
For primitive arrays, Arrays.sort() uses a highly optimized, dual-pivot Quicksort implementation. This is very fast on average.
Example: Sorting an int[]

import java.util.Arrays;
public class PrimitiveSortExample {
public static void main(String[] args) {
int[] numbers = {5, 1, 9, 3, 7, 2, 8, 4, 6};
System.out.println("Array before sorting: " + Arrays.toString(numbers));
// Sort the array in ascending order
Arrays.sort(numbers);
System.out.println("Array after sorting: " + Arrays.toString(numbers));
}
}
Output:
Array before sorting: [5, 1, 9, 3, 7, 2, 8, 4, 6]
Array after sorting: [1, 2, 3, 4, 5, 6, 7, 8, 9]
B. Sorting Object Arrays
For arrays of objects (like String, Integer, or any custom class), Arrays.sort() uses a Timsort algorithm. Timsort is a hybrid sorting algorithm derived from Merge Sort and Insertion Sort, known for its high performance and stability.
Crucial Requirement: The objects in the array must implement the Comparable interface. The sort() method uses the object's natural ordering (defined by its compareTo() method).
Example: Sorting a String[]

String objects already implement Comparable, so we can sort them directly.
import java.util.Arrays;
public class ObjectSortExample {
public static void main(String[] args) {
String[] fruits = {"Orange", "Apple", "Banana", "Grape", "Mango"};
System.out.println("Array before sorting: " + Arrays.toString(fruits));
// Sort the array of Strings
Arrays.sort(fruits);
System.out.println("Array after sorting: " + Arrays.toString(fruits));
}
}
Output:
Array before sorting: [Orange, Apple, Banana, Grape, Mango]
Array after sorting: [Apple, Banana, Grape, Mango, Orange]
Sorting Custom Objects
This is where Arrays.sort() becomes incredibly powerful. To sort an array of your own custom objects, you have two main options.
Option 1: Make your Class Implement Comparable
This is the most common approach. You define the "natural" sort order for your object by implementing the Comparable<T> interface and overriding the compareTo(T other) method.
compareTomethod: It should return:- A negative integer if
thisobject is less thanother. - Zero if
thisobject is equal toother. - A positive integer if
thisobject is greater thanother.
- A negative integer if
Example: Sorting an array of Student objects by their name
import java.util.Arrays;
// Step 1: The class must implement Comparable
class Student implements Comparable<Student> {
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{name='" + name + "', age=" + age + "}";
}
// Step 2: Override compareTo to define the natural order (by name)
@Override
public int compareTo(Student other) {
return this.name.compareTo(other.name); // Lexicographical comparison of names
}
}
public class CustomObjectSortExample {
public static void main(String[] args) {
Student[] students = {
new Student("Charlie", 20),
new Student("Alice", 22),
new Student("Bob", 21)
};
System.out.println("Array before sorting: " + Arrays.toString(students));
// Sort the array of Students
Arrays.sort(students);
System.out.println("Array after sorting: " + Arrays.toString(students));
}
}
Output:
Array before sorting: [Student{name='Charlie', age=20}, Student{name='Alice', age=22}, Student{name='Bob', age=21}]
Array after sorting: [Student{name='Alice', age=22}, Student{name='Bob', age=21}, Student{name='Charlie', age=20}]
Option 2: Use a Comparator (for Flexible Sorting)
What if you want to sort the same Student array by age sometimes and by name other times? Modifying the compareTo method every time is not practical.
This is where a Comparator comes in. A Comparator is a separate object that defines a custom sorting order without changing the class itself. You pass the Comparator to Arrays.sort().
There are two ways to create a Comparator:
A) As an Anonymous Inner Class (Traditional Java)
import java.util.Arrays;
import java.util.Comparator; // Import Comparator
// ... (Student class from above) ...
public class ComparatorSortExample {
public static void main(String[] args) {
Student[] students = {
new Student("Charlie", 20),
new Student("Alice", 22),
new Student("Bob", 21)
};
System.out.println("--- Sorting by Age ---");
// Sort using an anonymous Comparator to compare by age
Arrays.sort(students, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
return Integer.compare(s1.age, s2.age); // Compare by age
}
});
System.out.println("Array after sorting by age: " + Arrays.toString(students));
}
}
B) Using a Lambda Expression (Modern Java 8+)
This is much more concise and readable. It's the preferred modern approach.
import java.util.Arrays;
import java.util.Comparator;
// ... (Student class from above) ...
public class LambdaComparatorExample {
public static void main(String[] args) {
Student[] students = {
new Student("Charlie", 20),
new Student("Alice", 22),
new Student("Bob", 21)
};
System.out.println("--- Sorting by Age (Lambda) ---");
// Sort using a lambda expression
Arrays.sort(students, (s1, s2) -> Integer.compare(s1.age, s2.age));
System.out.println("Array after sorting by age: " + Arrays.toString(students));
System.out.println("\n--- Sorting by Name (Lambda) ---");
// Sort by name again, using a different lambda
Arrays.sort(students, (s1, s2) -> s1.name.compareTo(s2.name));
System.out.println("Array after sorting by name: " + Arrays.toString(students));
}
}
Output of both examples:
--- Sorting by Age (Lambda) ---
Array after sorting by age: [Student{name='Charlie', age=20}, Student{name='Bob', age=21}, Student{name='Alice', age=22}]
--- Sorting by Name (Lambda) ---
Array after sorting by name: [Student{name='Alice', age=22}, Student{name='Bob', age=21}, Student{name='Charlie', age=20}]
Overloaded Methods: Sorting a Range of an Array
Arrays.sort() also has overloaded versions that let you sort only a specific range of an array, defined by a fromIndex (inclusive) and toIndex (exclusive).
Syntax:
Arrays.sort(arrayName, fromIndex, toIndex);
Example:
import java.util.Arrays;
public class RangeSortExample {
public static void main(String[] args) {
int[] numbers = {10, 5, 8, 20, 15, 3, 9, 1};
System.out.println("Original array: " + Arrays.toString(numbers));
// Sort only the subarray from index 2 (inclusive) to 6 (exclusive)
// This will sort the elements {8, 20, 15, 3}
Arrays.sort(numbers, 2, 6);
System.out.println("Array after sorting range [2, 6): " + Arrays.toString(numbers));
}
}
Output:
Original array: [10, 5, 8, 20, 15, 3, 9, 1]
Array after sorting range [2, 6): [10, 5, 3, 8, 15, 20, 9, 1]
Note: The elements at indices 0, 1, 6, and 7 remain unchanged.
Performance and Complexity
| Array Type | Algorithm | Average Time Complexity | Worst-Case Time Complexity | Notes |
|---|---|---|---|---|
| Primitive Arrays | Dual-Pivot Quicksort | O(n log n) |
O(n²) |
Extremely fast in practice. The n² case is rare. |
| Object Arrays | Timsort | O(n log n) |
O(n log n) |
Stable (preserves order of equal elements). Excellent for real-world data. |
Stability: An algorithm is stable if two objects with equal keys (e.g., two students with the same age) appear in the same order in the sorted output as they did in the input. Timsort is stable, while the Quicksort used for primitives is not.
Summary: When to Use Arrays.sort()
-
YES, use it when:
- You need a quick and easy way to sort any array.
- You are sorting primitive types.
- You are sorting objects and their natural ordering (
Comparable) is sufficient. - You need to sort a subarray.
-
Consider alternatives or be cautious when:
- You need a stable sort for primitive arrays (since the default Quicksort is not stable). You would have to box the primitives into objects (e.g.,
Integer[]) and then sort. - You have very specific, complex, or multiple sorting requirements for the same object class. In this case, using multiple
Comparators is the best approach. - You are working in a highly concurrent environment and need a thread-safe sort.
Arrays.sort()is not thread-safe. You would need to use external libraries like Java'sparallelSort()or others designed for concurrency.
- You need a stable sort for primitive arrays (since the default Quicksort is not stable). You would have to box the primitives into objects (e.g.,
