Java – Sort Integer Array

To sort an integer array in Java, call Arrays.sort() method and pass the array as argument. Arrays.sort() method sorts the given array in-place in ascending order.

Examples

In the following example, we take an integer array and sort it in ascending order using Arrays.sort().

Main.java

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int arr[] = {4, 1, 3, 2, 6, 5};
        System.out.println("Original : " + Arrays.toString(arr));

        Arrays.sort(arr);
        System.out.println("Sorted   : " + Arrays.toString(arr));
    }
}

Output

Original : [4, 1, 3, 2, 6, 5]
Sorted   : [1, 2, 3, 4, 5, 6]

To sort the array in descending order, we may first sort the given array in ascending order, and then reverse it.

ADVERTISEMENT

Conclusion

In this Java Tutorial, we learned how to sort an integer array using Arrays.sort() method with examples.