How to use the Arrays.sort() method in Java

The built-in java.util.Arrays class has a method called sort() which can be used to sort an array in-place.

Syntax

svg viewer

If starting_index and ending_index are not specified, the whole array is sorted.

Code

The following code snippet demonstrates how Arrays.sort() can be used to sort an integer array:

import java.util.Arrays;
class Program {
public static void main( String args[] ) {
int [] arr = {5, -2, 23, 7, 87, -42, 509};
System.out.println("The original array is: ");
for (int num: arr) {
System.out.print(num + " ");
}
Arrays.sort(arr);
System.out.println("\nThe sorted array is: ");
for (int num: arr) {
System.out.print(num + " ");
}
}
}

The code snippet below uses the optional starting and ending indexes to sort the array within the specified bounds only:

import java.util.Arrays;
class Program {
public static void main( String args[] ) {
int [] arr = {5, -2, 23, 7, 87, -42, 509};
System.out.println("The original array is: ");
for (int num: arr) {
System.out.print(num + " ");
}
Arrays.sort(arr, 3, 6);
System.out.println("\nThe sorted array (from position 3 to 6) is: ");
for (int num: arr) {
System.out.print(num + " ");
}
}
}
Copyright ©2024 Educative, Inc. All rights reserved