Java – Sort String Array
To sort a String 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. The sorting of strings happen lexicographically.
Examples
In the following example, we take a string 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) { String arr[] = {"banana", "cherry", "apple"}; System.out.println("Original : " + Arrays.toString(arr)); Arrays.sort(arr); System.out.println("Sorted : " + Arrays.toString(arr)); } }
Output
Original : [banana, cherry, apple] Sorted : [apple, banana, cherry]
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 a string array using Arrays.sort() method with examples.