Java.util.Arrays.sort() Method



Description

The java.util.Arrays.sort(long[], int, int) method sorts the specified range of the specified array of longs into ascending numerical order. The range to be sorted extends from index fromIndex, inclusive, to index toIndex, exclusive.

Declaration

Following is the declaration for java.util.Arrays.sort() method

public static void sort(long[] a, int fromIndex, int toIndex)

Parameters

  • a − This is the array to be sorted.

  • fromIndex − This is the index of the first element (inclusive) to be sorted.

  • toIndex − This is the index of the last element (exclusive) to be sorted .

Return Value

This method does not return any value.

Exception

  • IllegalArgumentException − if fromIndex > toIndex

  • ArrayIndexOutOfBoundsException − if fromIndex < 0 or toIndex > a.length

Example

The following example shows the usage of java.util.Arrays.sort() method.

package com.tutorialspoint;

import java.util.Arrays;

public class ArrayDemo {
   public static void main(String[] args) {

      // initializing unsorted long array
      long lArr[] = {31, 13, 12, 98, 11};

      // let us print all the elements available in list
      for (long number : lArr) {
         System.out.println("Number = " + number);
      }
      
      // sorting array from index 1 to 3
      Arrays.sort(lArr, 1, 3);

      // let us print all the elements available in list
      System.out.println("long array with some sorted values(1 to 3) is:");
      for (long number : lArr) {
         System.out.println("Number = " + number);
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Number = 31
Number = 13
Number = 12
Number = 98
Number = 11
long array with some sorted values(1 to 3) is:
Number = 31
Number = 12
Number = 13
Number = 98
Number = 11
java_util_arrays.htm
Advertisements