How to Sort Array of Strings in Java Quickly and Easily
To sort an array of strings in Java, use
Arrays.sort(array) from the java.util.Arrays class. This method sorts the array in place in ascending alphabetical order.Syntax
The syntax to sort an array of strings is simple:
Arrays.sort(array): Sorts the given array in ascending order.
Here, array is the string array you want to sort.
java
import java.util.Arrays; public class SortExample { public static void main(String[] args) { String[] array = {"banana", "apple", "cherry"}; Arrays.sort(array); } }
Example
This example shows how to sort an array of strings alphabetically and print the sorted array.
java
import java.util.Arrays; public class SortStringsExample { public static void main(String[] args) { String[] fruits = {"banana", "apple", "cherry", "date"}; Arrays.sort(fruits); for (String fruit : fruits) { System.out.println(fruit); } } }
Output
apple
banana
cherry
date
Common Pitfalls
Common mistakes when sorting string arrays include:
- Trying to sort without importing
java.util.Arrays. - Expecting
Arrays.sort()to return a new array (it sorts in place). - Not handling
nullvalues in the array, which causeNullPointerException.
Always ensure the array is not null and contains no null elements before sorting.
java
import java.util.Arrays; public class SortNullExample { public static void main(String[] args) { String[] names = {"John", null, "Alice"}; // This will throw NullPointerException // Arrays.sort(names); // Correct approach: remove or handle nulls before sorting String[] filtered = Arrays.stream(names) .filter(s -> s != null) .toArray(String[]::new); Arrays.sort(filtered); for (String name : filtered) { System.out.println(name); } } }
Output
Alice
John
Quick Reference
Summary tips for sorting string arrays in Java:
- Use
Arrays.sort(array)to sort in ascending order. - Sorting is done in place; the original array changes.
- Handle
nullvalues before sorting to avoid errors. - For custom order, use
Arrays.sort(array, Comparator).
Key Takeaways
Use Arrays.sort(array) to sort string arrays alphabetically in Java.
Sorting modifies the original array; no new array is created.
Always import java.util.Arrays before using sort.
Avoid null values in the array or handle them before sorting.
For custom sorting, use a Comparator with Arrays.sort.