How to sort an array


A common mistake for a beginner to Java is to try and write some more or less complex method for sorting an array when in fact it can be done with just one line of code.
The Arrays class has a static method called sort which exists in many overloaded versions so you can pass in an array of any primitive type, or pass in an array of Strings or other Objects.
Since it is the reference of the array that is passed to the sort method nothing needs to be returned from it, the array is altered through the reference.
The example below shows two nearly identical methods, one that sorts an int array, and one that sorts an array of Strings.


import java.util.Arrays;

/**
 *
 * @author javadb.com
 */

public class Main {
    
    /**
     * Example method for sorting an int array
     */

    public void sortIntArray() {
        
        int[] arrayToSort = new int[] {48, 5, 89, 80, 81, 23, 45, 16, 2};
        
        Arrays.sort(arrayToSort);
        
        for (int i = 0; i < arrayToSort.length; i++)
            System.out.println(arrayToSort[i]);
    }

    /**
     * Example method for sorting a String array
     */

    public void sortStringArray() {
        
        String[] arrayToSort = new String[] {"Oscar", "Charlie", "Ryan", "Adam", "David"};
        
        Arrays.sort(arrayToSort);
        
        for (int i = 0; i < arrayToSort.length; i++)
            System.out.println(arrayToSort[i]);
    }
    
    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        Main main = new Main();
        main.sortIntArray();
        main.sortStringArray();
    }
}

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: