Java .sort()
Published May 25, 2022
The .sort() method of the Arrays class sorts a given array into ascending order.
Syntax
Arrays.sort(array)
Arrays.sort(array, start, end)
Where array is the array being sorted. start and end indices can also be specified and the sort will be confined to the given range.
Example
The following example creates an array and then sorts it.
import java.util.*;public class Example {public static void main(String args[]) {String[] a = {"one", "two", "three", "four", "five", "six"};Arrays.sort(a);for (int i = 0; i < 6; i++) {System.out.println(a[i]);}}}
This will output the following:
fivefouronesixthreetwo
Learn Java on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours