For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
46. Packages in Java
53. Java Collection
56. Generics In Java
57. Java Interfaces
60. Streams in Java
63. Thread in Java
67. Deadlock in Java
74. Applet in Java
75. Java Swing
76. Java Frameworks
78. JUnit Testing
81. Jar file in Java
82. Java Clean Code
86. Java 8 features
87. String in Java
93. HashMap in Java
98. Enum in Java
101. Hashcode in Java
105. Linked List in Java
109. Array Length in Java
111. Split in java
112. Map In Java
115. HashSet in Java
118. DateFormat in Java
121. Java List Size
122. Java APIs
128. Identifiers in Java
130. Set in Java
132. Try Catch in Java
133. Bubble Sort in Java
135. Queue in Java
142. Jagged Array in Java
144. Java String Format
145. Replace in Java
146. charAt() in Java
147. CompareTo in Java
151. parseInt in Java
153. Abstraction in Java
154. String Input in Java
156. instanceof in Java
157. Math Floor in Java
158. Selection Sort Java
159. int to char in Java
164. Deque in Java
172. Trim in Java
173. RxJava
174. Recursion in Java
175. HashSet Java
177. Square Root in Java
190. Javafx
Sorting is a common task in programming. Whether you are organizing numbers, names, or custom data, sorting helps present information clearly and efficiently. In Java, arrays can be sorted easily using built-in methods provided by the Arrays class.
This blog will guide you through how to sort an array in Java-from basic usage to advanced techniques like custom sorting and using comparators. You’ll also learn how to sort strings, subarrays, and arrays in descending order.
To master such programming skills, software engineering courses offer hands-on guidance and structured learning paths.
Sorting in Java programming means arranging array elements in a specific order—either ascending or descending. Java provides built-in support for sorting primitive and object arrays using the Arrays.sort() method. You can also define your own sorting logic using Comparator or Comparable.
Example:
int[] numbers = {5, 2, 9, 1};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
Output:
[1, 2, 5, 9]
Explanation: The Arrays.sort() method arranges the integers in ascending order.
Take your skills to the next level with these highly rated courses.
Java provides multiple overloaded versions of the Arrays.sort() method to handle different types of arrays and custom logic.
Arrays.sort(array); // Sorts entire array
Arrays.sort(array, fromIndex, toIndex); // Sorts a specific range
Arrays.sort(array, comparator); // Custom sort using comparator
The method is simple to use and supports both primitive and object arrays.
Also read: Creating a Dynamic Array in Java
Before sorting, you may need to access or update elements in the array. Java arrays are zero-indexed and can be updated directly using their index.
Example:
int[] arr = {10, 20, 30};
System.out.println(arr[1]); // Access
arr[1] = 25; // Modify
System.out.println(arr[1]);
Output:
20
25
Explanation: You access and modify the array using its index. Here, the second element is updated from 20 to 25.
Must explore:
Java lets you sort a specific portion of an array using Arrays.sort(array, fromIndex, toIndex). The fromIndex is inclusive, and toIndex is exclusive.
Example:
int[] data = {8, 4, 2, 9, 5};
Arrays.sort(data, 1, 4);
System.out.println(Arrays.toString(data));
Output:
[8, 2, 4, 9, 5]
Explanation: Only the elements from index 1 to 3 are sorted (4, 2, 9 becomes 2, 4, 9).
Also check: How to Convert String into Array in Java
Sorting in Descending Order
Java doesn't directly support descending order for primitive arrays. But you can convert it to an object array and use Collections.reverseOrder().
Example:
Integer[] nums = {10, 4, 7, 2};
Arrays.sort(nums, Collections.reverseOrder());
System.out.println(Arrays.toString(nums));
Output:
[10, 7, 4, 2]
Explanation: The array is sorted in descending order using a comparator from Collections.
You can sort string arrays in reverse alphabetical order using Collections.reverseOrder() just like numeric arrays.
Example:
String[] names = {"Nitin", "Sita", "Anamika"};
Arrays.sort(names, Collections.reverseOrder());
System.out.println(Arrays.toString(names));
Output:
[Nitin, Sita, Anamika]
Explanation: The names are arranged from Z to A using reverse order.
To apply custom sorting rules, use the Comparator interface. It helps define sorting logic like sorting by string length or specific attributes.
Example:
String[] cities = {"Delhi", "Mumbai", "Agra"};
Arrays.sort(cities, (a, b) -> a.length() - b.length());
System.out.println(Arrays.toString(cities));
Output:
[Agra, Delhi, Mumbai]
Explanation: Cities are sorted by their string length using a custom comparator.
Java objects can implement the Comparable interface to define their natural order using the compareTo() method.
Example:
class Product implements Comparable<Product> {
int price;
Product(int price) {
this.price = price;
}
public int compareTo(Product p) {
return this.price - p.price;
}
public String toString() {
return price + "";
}
}
Product[] products = {
new Product(300),
new Product(150),
new Product(200)
};
Arrays.sort(products);
System.out.println(Arrays.toString(products));
Output:
[150, 200, 300]
Explanation: Products are sorted by price using their natural order defined in compareTo().
Must read: Multidimensional Array in Java
Sorting is essential in many applications:
1. E-commerce: Sort product listings by price, rating, or popularity to improve user experience and help customers make faster purchase decisions.
2. Search Algorithms: Algorithms like binary search require sorted arrays to work efficiently, reducing search time and improving performance.
3. Leaderboards: Sort player scores or performance metrics to display rankings in games, contests, or quiz platforms.
4. Data Analysis: Sort numeric or textual data to identify trends, outliers, or prepare organized reports for business insights.
Sorting arrays in Java is simple yet powerful. With Arrays.sort() and custom comparators, you can handle a wide range of sorting needs—numbers, strings, or custom objects. Sorting is essential for organizing and analyzing data efficiently in real-world Java applications.
To sort a 2D array, use Arrays.sort() with a custom comparator. You must define the sorting logic for the inner arrays—commonly based on the first or second element. Java doesn’t support direct sorting of 2D arrays without writing a custom comparator.
Yes, you can preserve the original array by first copying it using Arrays.copyOf() or System.arraycopy() and then sorting the copy. This way, the original data remains unchanged while you work on the sorted version.
You can loop through the array and check if each element is smaller than or equal to the next one. For large arrays, this manual check avoids unnecessary sorting and improves performance in some use cases.
For primitive types, Arrays.sort() uses Dual-Pivot Quicksort with average time complexity O(n log n). For object arrays, it uses TimSort, which also offers O(n log n) performance and is optimized for partially sorted arrays.
Use a custom Comparator with thenComparing() for multi-field sorting. For example, you can sort employees by department and then by salary. This approach ensures more fine-grained and logical ordering of complex data.
No, reverse sorting with Collections.reverseOrder() requires an object array like Integer[]. For primitive arrays like int[], you must manually reverse the sorted array or use streams to box and sort them.
You can use Java Streams for sorting by converting arrays to streams using Arrays.stream(), applying .sorted(), and collecting the result. For example, Arrays.stream(arr).sorted().toArray() returns a new sorted array.
If the array is null, Arrays.sort() will throw a NullPointerException. Always check for null before sorting or wrap your sorting logic inside a null-safe condition to prevent runtime errors.
No, Arrays.sort() is not thread-safe. If multiple threads access and modify the array concurrently, you must synchronize it manually or use concurrent collections like CopyOnWriteArrayList for thread-safe operations.
You can sort a character array just like integers using Arrays.sort(charArray). It will sort characters in their Unicode order, which is usually alphabetical for standard English characters.
Yes, you can implement bubble sort, insertion sort, or merge sort manually for educational or specific performance reasons. However, for most practical use cases, the built-in Arrays.sort() is more efficient and optimized.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author|900 articles published
Previous
Next
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.