View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

How to Sort an Array in Java– A Complete Beginner’s Guide with Examples

Updated on 19/05/20254,198 Views

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.

How to Sort an Array in Java?

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.

Syntax of Arrays.sort() Method

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

Accessing and Modifying Array Elements 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: 

Sorting a Subarray

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.

Sorting String Arrays in Descending Alphabetical Order

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.

Custom Sorting with Comparator

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.

Natural Sorting with Comparable Interface

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

Use Cases of Sorting Arrays 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.

Best Practices to Sort an array in Java

  • Prefer Arrays.sort() for built-in sorting.
  • Use Comparator for custom sort logic.
  • Convert to object arrays for descending order.
  • Avoid sorting very large arrays in performance-critical code without benchmarking.
  • Use stable sorts where original order matters for equal elements.

Conclusion

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.

FAQs

1. How do I sort a 2D array in Java?

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.

2. Can I sort an array in Java without modifying the original array?

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.

3. How do I check if an array is already sorted in Java?

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.

4. What is the time complexity of Arrays.sort() in Java?

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.

5. How do I sort an array of objects by multiple fields in Java?

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.

6. Can I sort an array in reverse order without converting it to an object array?

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.

7. How can I sort an array using Java Streams?

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.

8. What happens if the array passed to Arrays.sort() is null?

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.

9. Is sorting an array thread-safe in Java?

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.

10. How do I sort a character array in Java?

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.

11. Can I use bubble sort or other algorithms manually in Java?

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.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

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.