How To Use Arrays.sort Function In Java
JAVA Programming Language Java Arrays

How To Use Arrays.sort Function In Java

In this article, we are discussing How To Use Arrays.sort Function In Java to sort the array. We recently published an article on how to sort an array in java in the very simplest and easy method. What is the Arrays.sort()? The answer is it is a built-in function and the function of this function is also clear from his name that this function sorts the arrays in ascending order.

How To Use Arrays.sort Function In Java:

For using this built-in function we have to import the package of arrays(import java.util.Arrays:). Now simply declare an array and take the value of the array using the scanner class in a loop. After taking the elements of the array from the user now use another loop to print those elements and display a message before this loop(“Before Sorting”) print this message before printing the elements and outside the loop.

After printing the elements simply use this built-in function but this time passing the array name as an argument as we show you in the below program and then again print the message(After Sorting) after this message now you have to print the elements to see that your array will be sorted.

Source Code:

import java.util.Arrays;
import java.util.*;
public class Sorting {
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
    int [] array = new int [5];
    System.out.println("Enter The Elements Of The Array : ");
    for(int i=0 ; i<array.length; i++){
        array[i] = sc.nextInt();
    }
    System.out.println("Before Sorting ");
    for (int i = 0; i < array.length; i++) {
        System.out.print(array[i]+"\t");
    }
    System.out.println();
    System.out.println("After Sorting : ");
   Arrays.sort(array);
   for (int i = 0; i < array.length; i++) {
    System.out.print(array[i]+"\t");
   }
    } 

}

Output Of The Program:

How To Use Arrays.sort() Function In Java
How To Use Arrays.sort() Function In Java

 

 

 

 

 

From the above program, we conclude and understand How To Use Arrays.sort() Function In Java.

Video Link:

Leave a Reply

Your email address will not be published. Required fields are marked *