Arrays.sort(long[], int, int) in Java

Arrays.sort(long[], int, int): This method is available in java.util.Arrays class of Java.

Syntax:

void java.util.Arrays.sort(long[] a, int fromIndex, int toIndex)

This method takes three arguments one of type long array and the rest two are of type int as its parameters. This method sorts the specified range of the array into ascending order.

Parameters: Three parameters are required for this method.

a: the array to be sorted.

fromIndex: the index of the first element, inclusive, to be sorted.

toIndex: the index of the last element, exclusive, to be sorted.

Throws:

1. IllegalArgumentException - if fromIndex > toIndex.

2. ArrayIndexOutOfBoundsException - if fromIndex < 0 or toIndex > a.length.

Approach 1: When no exceptions

Java

import java.util.Arrays;

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

        long a[] = { 12, 6, 6, 2, 4, 56, 23 };

        int fromIndex = 0, toIndex = 3;
        Arrays.sort(a, fromIndex, toIndex);

        System.out.println(Arrays.toString(a));
    }
}

Output:

[6, 6, 12, 2, 4, 56, 23]


Approach 2: IllegalArgumentException 

Java

import java.util.Arrays;

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

        long a[] = { 12, 6, 6, 2, 4, 56, 23 };

        int fromIndex = 4, toIndex = 3;
        Arrays.sort(a, fromIndex, toIndex);

        System.out.println(Arrays.toString(a));
    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: fromIndex(4) > toIndex(3) at java.base/java.util.Arrays.rangeCheck(Arrays.java:718) at java.base/java.util.Arrays.sort(Arrays.java:160)



Approach 3: ArrayIndexOutOfBoundsException

Java

import java.util.Arrays;

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

        long a[] = { 12, 6, 6, 2, 4, 56, 23 };

        int fromIndex = -1, toIndex = 3;
        Arrays.sort(a, fromIndex, toIndex);

        System.out.println(Arrays.toString(a));
    }
}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: -1 at java.base/java.util.Arrays.rangeCheck(Arrays.java:722) at java.base/java.util.Arrays.sort(Arrays.java:160)


No comments:

Post a Comment