Homeβ€Ί Javaβ€Ί Array Sorting in Java: Arrays.sort() Explained From Scratch

Array Sorting in Java: Arrays.sort() Explained From Scratch

In Plain English πŸ”₯
Imagine you have a messy stack of exam papers, each with a score written on top. Before you can hand them back in order from lowest to highest, you need to sort them. That's exactly what array sorting does β€” it takes a jumbled list of values stored in your program and rearranges them into a predictable order. Java has a built-in helper called Arrays.sort() that does this sorting for you automatically, the same way a tidy assistant would sort those papers without you lifting a finger.
⚑ Quick Answer
Imagine you have a messy stack of exam papers, each with a score written on top. Before you can hand them back in order from lowest to highest, you need to sort them. That's exactly what array sorting does β€” it takes a jumbled list of values stored in your program and rearranges them into a predictable order. Java has a built-in helper called Arrays.sort() that does this sorting for you automatically, the same way a tidy assistant would sort those papers without you lifting a finger.

Every real application deals with ordered data. A leaderboard ranks players by score. A contacts list shows names alphabetically. A shop sorts products by price. None of that is possible if your data is sitting in random order. Sorting is one of the most fundamental operations in programming, and the sooner you get comfortable with it, the faster you'll be able to build things that actually feel polished and useful.

Before sorting existed as a built-in feature, developers had to write dozens of lines of code manually swapping values around β€” a slow, error-prone nightmare. Java's Arrays utility class solves this entirely. It ships with a sort() method powered by a highly optimised algorithm under the hood, so you get fast, reliable sorting in a single line of code without needing to understand the internals.

By the end of this article you'll know how to sort primitive arrays in ascending order, reverse them into descending order, sort arrays of strings alphabetically, write a custom sort rule using a Comparator, and avoid the classic traps that trip up beginners. You'll walk away with working code you can drop straight into a real project.

Sorting a Basic Number Array With Arrays.sort()

Before you can sort anything, you need to import Java's Arrays class. It lives in the java.util package and it's the toolbox that contains sort() and many other helpful array utilities. Think of it like importing a specialised calculator β€” once it's imported, all its functions are available to you.

Arrays.sort() takes your array as an argument and sorts it in-place. 'In-place' means it rearranges the values inside the original array β€” it doesn't create a new one. After the method runs, your original variable now holds the sorted data. This is important to keep in mind because there's no 'undo' β€” the original order is gone.

For arrays of primitive numbers (int, double, long etc.), the default sort is always ascending β€” smallest value first, largest value last. This mirrors natural numeric order, the same way you'd read numbers on a number line from left to right.

The algorithm Java uses internally for primitive arrays is called Dual-Pivot Quicksort. You don't need to understand it yet, but know that it's extremely fast β€” even an array of a million numbers sorts in a fraction of a second.

SortStudentScores.java Β· JAVA
123456789101112131415161718192021222324252627
import java.util.Arrays; // Gives us access to the Arrays utility class

public class SortStudentScores {

    public static void main(String[] args) {

        // A class of 6 students just got their test results back β€” completely out of order
        int[] studentScores = { 78, 45, 92, 61, 33, 88 };

        // Print the scores BEFORE sorting so we can see the difference
        System.out.println("Before sorting: " + Arrays.toString(studentScores));

        // Arrays.sort() rearranges the values inside studentScores from low to high
        // No new array is created β€” the same array is modified directly
        Arrays.sort(studentScores);

        // Print the scores AFTER sorting β€” now lowest to highest
        System.out.println("After sorting:  " + Arrays.toString(studentScores));

        // We can now easily find the lowest score (index 0) and highest (last index)
        int lowestScore  = studentScores[0];
        int highestScore = studentScores[studentScores.length - 1];

        System.out.println("Lowest score:   " + lowestScore);
        System.out.println("Highest score:  " + highestScore);
    }
}
β–Ά Output
Before sorting: [78, 45, 92, 61, 33, 88]
After sorting: [33, 45, 61, 78, 88, 92]
Lowest score: 33
Highest score: 92
⚠️
Pro Tip:Always use Arrays.toString() when printing an array β€” printing the array variable directly (e.g. System.out.println(studentScores)) gives you a memory address like [I@6d06d69c, which is useless for debugging.

Sorting Strings Alphabetically and Numbers in Descending Order

Sorting strings works exactly the same way as sorting numbers β€” just call Arrays.sort() and Java handles the alphabetical ordering for you. Under the hood, Java compares strings character by character using their Unicode values, which means uppercase letters ('A' = 65) sort before lowercase letters ('a' = 97). For everyday words that share the same case, this just looks like normal A-to-Z ordering.

Now, what about descending order β€” highest to lowest? This is where things get slightly different. Arrays.sort() has no built-in 'reverse' flag for primitive arrays. The cleanest workaround for int[] is to sort ascending first, then reverse the array manually. Alternatively, you can switch from a primitive int[] to an Integer[] (the object wrapper version), which unlocks a second form of Arrays.sort() that accepts a Comparator β€” a rule that tells Java how to compare two items.

Comparators.reverseOrder() is a ready-made comparator that flips the sort direction. Think of it as telling Java: 'for every comparison you make, do the opposite of what you'd normally do.'

This section shows both approaches side by side so you can choose whichever fits your situation.

SortNamesAndRankings.java Β· JAVA
1234567891011121314151617181920212223242526272829303132
import java.util.Arrays;
import java.util.Collections; // Needed for Collections.reverseOrder()

public class SortNamesAndRankings {

    public static void main(String[] args) {

        // ── PART 1: Sort a String array alphabetically ──────────────────────
        String[] playerNames = { "Zara", "Ahmed", "Priya", "Luca", "Mei" };

        System.out.println("Names before sort: " + Arrays.toString(playerNames));

        Arrays.sort(playerNames); // Sorts A-to-Z using Unicode/alphabetical order

        System.out.println("Names after sort:  " + Arrays.toString(playerNames));

        // ── PART 2: Sort integers in DESCENDING order (highest first) ────────
        // We must use Integer[] (capital I β€” the object wrapper) NOT int[]
        // because Collections.reverseOrder() only works with objects, not primitives
        Integer[] highScores = { 1500, 3200, 800, 4750, 2100 };

        System.out.println("\nScores before sort: " + Arrays.toString(highScores));

        // Pass Collections.reverseOrder() as the second argument to flip the sort
        Arrays.sort(highScores, Collections.reverseOrder());

        System.out.println("Scores after sort:  " + Arrays.toString(highScores));

        // The top player's score is now conveniently sitting at index 0
        System.out.println("Top score belongs to: " + playerNames[0] + " with " + highScores[0]);
    }
}
β–Ά Output
Names before sort: [Zara, Ahmed, Priya, Luca, Mei]
Names after sort: [Ahmed, Luca, Mei, Priya, Zara]

Scores before sort: [1500, 3200, 800, 4750, 2100]
Scores after sort: [4750, 3200, 2100, 1500, 800]
Top score belongs to: Ahmed with 4750
⚠️
Watch Out:Collections.reverseOrder() does NOT work with int[] β€” it causes a compile error. You must use Integer[] (the wrapper class) instead. This is one of the most common beginner mistakes when trying to sort in reverse order.

Custom Sorting Rules With a Comparator (Sort by Word Length, Not Alphabet)

Sometimes alphabetical or numeric order isn't what you need. What if you want to sort a list of movie titles by how long the title is β€” shortest first? Or sort products by the number of characters in their name? This is where a custom Comparator comes in.

A Comparator is simply a rule that tells Arrays.sort() how to decide which of two elements should come first. You hand it two items β€” call them 'a' and 'b' β€” and your rule returns a negative number if 'a' should come first, a positive number if 'b' should come first, or zero if they're equal. Java uses this rule for every comparison it makes during the sort.

In modern Java (version 8 and above) you can write a Comparator as a lambda expression β€” a short, inline piece of logic that looks like an arrow: (a, b) -> someRule. This means you don't need to write a whole separate class just to define one comparison rule.

Once you understand this pattern, you can sort absolutely anything by any rule you can imagine β€” it's one of the most powerful and flexible tools in Java.

SortMovieTitlesByLength.java Β· JAVA
123456789101112131415161718192021222324252627282930313233343536373839404142
import java.util.Arrays;

public class SortMovieTitlesByLength {

    public static void main(String[] args) {

        String[] movieTitles = {
            "Inception",
            "Up",
            "The Dark Knight",
            "Dune",
            "Interstellar"
        };

        System.out.println("Titles before sort: " + Arrays.toString(movieTitles));

        // Custom Comparator using a lambda expression:
        // (a, b) -> Integer.compare(a.length(), b.length())
        //
        // For each pair of titles, compare their lengths:
        //   - If a is shorter than b  β†’ negative number β†’ a goes first
        //   - If a is longer than b   β†’ positive number β†’ b goes first
        //   - If equal length         β†’ 0               β†’ keep current order
        Arrays.sort(movieTitles, (a, b) -> Integer.compare(a.length(), b.length()));

        System.out.println("Titles sorted by length (short β†’ long):");

        // Loop through and print each title with its character count
        for (String title : movieTitles) {
            System.out.println("  " + title + " (" + title.length() + " chars)");
        }

        // BONUS: Reverse the lambda to get longest title first
        // Simply swap a and b in the comparison: compare(b.length(), a.length())
        Arrays.sort(movieTitles, (a, b) -> Integer.compare(b.length(), a.length()));

        System.out.println("\nTitles sorted by length (long β†’ short):");
        for (String title : movieTitles) {
            System.out.println("  " + title + " (" + title.length() + " chars)");
        }
    }
}
β–Ά Output
Titles before sort: [Inception, Up, The Dark Knight, Dune, Interstellar]
Titles sorted by length (short β†’ long):
Up (2 chars)
Dune (4 chars)
Inception (9 chars)
Interstellar (12 chars)
The Dark Knight (15 chars)

Titles sorted by length (long β†’ short):
The Dark Knight (15 chars)
Interstellar (12 chars)
Inception (9 chars)
Dune (4 chars)
Up (2 chars)
πŸ”₯
Interview Gold:Interviewers love asking you to 'sort by a custom field'. The pattern is always the same: Arrays.sort(array, (a, b) -> Integer.compare(a.someProperty, b.someProperty)). Memorise this shape and you can adapt it to any sorting problem in seconds.
AspectArrays.sort() β€” AscendingArrays.sort() with reverseOrder()
Works with primitives (int[])?Yes β€” directlyNo β€” must use Integer[] wrapper
Works with objects (Integer[], String[])?YesYes
Default directionAscending (low β†’ high, A β†’ Z)Descending (high β†’ low, Z β†’ A)
Custom sort rule possible?No β€” only natural orderYes β€” pass any Comparator lambda
Import requiredjava.util.Arraysjava.util.Arrays + java.util.Collections
PerformanceDual-Pivot Quicksort β€” O(n log n)Same algorithm, same performance
When to useDefault ordering is fineNeed reverse or custom ordering

🎯 Key Takeaways

  • Arrays.sort() sorts in-place β€” the original array is permanently changed, so copy it first if you need the original order preserved
  • Reverse order requires switching from int[] to Integer[] β€” primitives don't support Comparators, object wrappers do
  • Custom Comparators follow one pattern: (a, b) -> Integer.compare(a.field, b.field) β€” swap a and b to reverse direction
  • Always use Arrays.toString() when printing arrays β€” the raw variable prints a useless memory address, not the values

⚠ Common Mistakes to Avoid

  • βœ•Mistake 1: Using Collections.reverseOrder() on a primitive int[] array β€” This causes a compile-time error ('no suitable method found for sort(int[], Comparator)') because reverseOrder() only works with object types. Fix: change int[] to Integer[] and the error disappears immediately.
  • βœ•Mistake 2: Forgetting that Arrays.sort() modifies the original array β€” If you sort an array and later need the original order, it's gone. Fix: make a copy first using Arrays.copyOf(originalArray, originalArray.length), sort the copy, and leave the original untouched.
  • βœ•Mistake 3: Printing an array with System.out.println(myArray) and getting a garbage memory address like [I@7852e922 β€” This happens because arrays don't override toString() in Java. Fix: always wrap the array in Arrays.toString(myArray) before printing, which gives you the readable [1, 2, 3] format.

Interview Questions on This Topic

  • QWhat sorting algorithm does Arrays.sort() use internally for primitive arrays vs object arrays, and why are they different?
  • QHow would you sort an array of strings by their length in descending order using a single line of code?
  • QIf I call Arrays.sort() on an int[] and then need the original unsorted data back, what should I have done before calling sort() β€” and what class would you use?

Frequently Asked Questions

How do I sort an array in descending order in Java?

Change your array type from int[] to Integer[] (the object wrapper), then call Arrays.sort(yourArray, Collections.reverseOrder()). You'll need to import both java.util.Arrays and java.util.Collections. This doesn't work on primitive int[] arrays because Comparators only operate on objects.

Does Arrays.sort() change the original array in Java?

Yes β€” Arrays.sort() sorts in-place, meaning it rearranges the elements inside the same array you passed in. There's no return value and no new array is created. If you need the original unsorted order preserved, create a copy first using Arrays.copyOf(original, original.length) and sort the copy instead.

Why does printing a Java array directly show something like [I@6d06d69c instead of the values?

Java arrays don't override the toString() method, so printing them directly shows their internal type identifier and memory address. Wrap the array in Arrays.toString(yourArray) before passing it to System.out.println() and you'll see the actual values formatted as [1, 2, 3] like you'd expect.

πŸ”₯
TheCodeForge Editorial Team Verified Author

Written and reviewed by senior developers with real-world experience across enterprise, startup and open-source projects. Every article on TheCodeForge is written to be clear, accurate and genuinely useful β€” not just SEO filler.

← PreviousMulti-dimensional Arrays in JavaNext β†’Array Searching in Java
Forged with πŸ”₯ at TheCodeForge.io β€” Where Developers Are Forged