Arrays.copyOfRange(double[], int, int) in Java

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

Syntax:

double[] java.util.Arrays.copyOfRange(double[] original, int from, int to)

This method takes three arguments one of type double array and the rest two are of type int as its parameters. This method copies the specified range of the specified array into a new array.

Parameters: Three parameters are required for this method.

original: the array from which a range is to be copied.

from: the initial index of the range to be copied, inclusive.

to: the final index of the range to be copied, exclusive.

Returns: a new array containing the specified range from the original array, truncated or padded with zeros to obtain the required length.

Throws:

1. ArrayIndexOutOfBoundsException - if from < 0or from > original.length.

2. IllegalArgumentException - if from > to.

3. NullPointerExceptionif original is null.

Approach 1: When no exceptions

Java

import java.util.Arrays;

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

        double orininal[] = { 1, 2, 3, 4 };
        int from = 0, to = 2;
        System.out.println(Arrays.toString(Arrays.copyOfRange(orininal,
from, to)));
    }
}

Output:

[1.0, 2.0]


Approach 2: ArrayIndexOutOfBoundsException

Java

import java.util.Arrays;

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

        double orininal[] = { 1, 2, 3, 4 };
        int from = -1, to = 2;
        System.out.println(Arrays.toString(Arrays.copyOfRange(orininal,
from, to)));
    }
}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: arraycopy: source index -1 out of bounds for double[4] at java.base/java.lang.System.arraycopy(Native Method) at java.base/java.util.Arrays.copyOfRange(Arrays.java:4038)



Approach 3: IllegalArgumentException

Java

import java.util.Arrays;

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

        double orininal[] = { 1, 2, 3, 4 };
        int from = 4, to = 2;
        System.out.println(Arrays.toString(Arrays.copyOfRange(orininal,
from, to)));
    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: 4 > 2 at java.base/java.util.Arrays.copyOfRange(Arrays.java:4036)



Approach 4: NullPointerException 

Java

import java.util.Arrays;

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

        double orininal[] = null;
        int from = 0, to = 2;
        System.out.println(Arrays.toString(Arrays.copyOfRange(orininal,
from, to)));
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because "original" is null at java.base/java.util.Arrays.copyOfRange(Arrays.java:4038)


No comments:

Post a Comment