Java.util.Arrays.sort() Method



Description

The java.util.Arrays.sort(byte[] a, int fromIndex, int toIndex) method sorts the specified range of the specified array of bytes 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(byte[] 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 byte array
      byte bArr[] = {10,7,4,37,29};

      // let us print all the elements available in list
      for (byte number : bArr) {
         System.out.println("Number = " + number);
      }

      // sorting array from index 1 to 4
      Arrays.sort(bArr, 1, 4);

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

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

Number = 10
Number = 7
Number = 4
Number = 37
Number = 29
Byte array with some sorted values(1 to 4) is:
Number = 10
Number = 4
Number = 7
Number = 37
Number = 29
java_util_arrays.htm
Advertisements