Task: Write a Java Program to use Java Arrays sort Method to Sort Arrays in Ascending Order. Use arrays containing of different types of data that is arrays of integers, arrays of doubles or arrays of strings strings etc.
What is Java Arrays sort Method?
Actually there is a class in java.util package known as Arrays class. This Arrays class contains a sort method. This sort() method is used to sort any type of array in ascending order.
What is Advantage of using sort() Method?
Therefore, sort method will save effort and time of the programmer. Because, the programmers need not writing a lot of code code to describe his own logic for sorting arrays.
Syntax of Arrays.sort() Method
The simplest general form of using Arrays.sort() method is as follows:
sort() method can sort arrays of byte, short, integer, long, float, double, char, or String etc.
Example: Use Arrays.sort() to Sort Array of integers
The output will be:
Sorted Array in ascending order is:
10, 20, 30, 40, 50,
We have used an array of integers, initialized with values. You can input numbers in array at run time, view this Java program.
Using sort() to sort Strings
The output of Java program to sort array of strings is:
Sorted Array of strings in ascending order is:
Apple, Banana, Mango, Orange, Peach,
How to use Arrays sort() for double numbers arrays
The output of sorting array of double values is:
Sorted Array of double values in ascending order is:
1.44, 9.95, 10.55, 30.36, 110.12,
So we have seen many example programs to sort arrays in ascending order using built in sort() method of Arrays class. Remember that Arrays class is in java.util package. Therefore we have to use an import statement in our Java program:
You may also like to read How to use Java Arrays class’s sort() method to sort numbers in descending order.