Arrays · Lesson 6/9
67%
⏱ 10–15 min

Method Arrays.sort()

Sorting arrays is a common task in Java application development. The Arrays.sort() method from the java.util package allows you to sort the elements of an array in ascending order quickly and efficiently.

Here’s a basic example showing how to sort an array of integers:

import java.util.Arrays;

public class ArraysSortExample1 {
    public static void main(String[] args) {
        int[] array = new int[]{3, 1, 5, 6, 8};
        Arrays.sort(array);
        System.out.println(Arrays.toString(array));
    }
}

Output:

[1, 3, 5, 6, 8]

The Arrays.sort() method uses a Dual-Pivot Quicksort algorithm for primitive types, which is optimized for performance and handles most input efficiently. For object arrays, such as String[], it uses a modified mergesort algorithm that is stable.

You can also sort arrays of other data types such as double[], char[], or arrays of objects using custom comparators with Arrays.sort(). This makes it a powerful and flexible tool for ordering data in Java.

Sorting is essential in many real-world scenarios, such as displaying sorted lists, performing efficient searches, or preparing data for binary search.

Java Core

1. Java Introduction
2. Run Your First Java App
3. Java Syntax
4. Java Operations
5. Operators
6. Arrays
7. Sorting Algorithms
8. Git & GitHub
9. OOP Basics
10. Lambda Expressions
11. Stream API
12. Inner Classes and Exceptions
‹ Previous lesson Next lesson ›