Java Arrays.sort() Syntax
sort() is a static method of the Arrays class. It returns nothing and reorders the array itself. In the second form, fromIndex is inclusive and toIndex is exclusive.
Java Sort Array Examples
The following are examples of sorting an array in Java. You can run any of these examples in the online Java code runner and replace the values to sort your own data.
Sort an int array in ascending order
Arrays.toString() prints the sorted elements. Printing the array itself shows only its type and hash code.
Sort an array in descending order
Collections.reverseOrder() returns a Comparator that reverses the natural order. It works with Integer[], but not with int[]. To sort an int array in descending order, sort it and then reverse it in a loop.
Sort an array of strings
Strings are compared by the Unicode values of their characters, so uppercase letters come before lowercase ones. String.CASE_INSENSITIVE_ORDER sorts them ignoring case.
Sort part of an array
Arrays.sort(numbers, 1, 4) sorts the elements at indexes 1, 2 and 3 and leaves the rest in place.
Sort an array of objects by a field
Comparator.comparingInt() builds a Comparator from a field of the object. Here, people are sorted by age.