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

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

Syntax:

long[] java.util.Arrays.copyOf(long[] original, int newLength)

This method takes two arguments one of type long array and the other of type int as its parameters. This method copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.

Parameters: Two parameters are required for this method.

original: the array to be copied.

newLength: the length of the copy to be returned.

Returns: a copy of the original array, truncated or padded with zeros to obtain the specified length.

Throws:

1. NegativeArraySizeException - if newLength is negative.

2. NullPointerException - if original is null.

Approach 1: When no exceptions

Java

import java.util.Arrays;

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

        long original[] = { 1, 2, 10, 5 };

        int newLength = 3;

        System.out.println(Arrays.toString(Arrays.copyOf(original,
newLength)));
    }
}

Output:

[1, 2, 10]


Approach 2: NegativeArraySizeException

Java

import java.util.Arrays;

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

        long original[] = { 1, 2, 10, 5 };

        int newLength = -3;

        System.out.println(Arrays.toString(Arrays.copyOf(original,
newLength)));
    }
}

Output:

Exception in thread "main" java.lang.NegativeArraySizeException: -3 at java.base/java.util.Arrays.copyOf(Arrays.java:3608)



Approach 3: NullPointerException 

Java

import java.util.Arrays;

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

        long original[] = null;
        int newLength = 3;

        System.out.println(Arrays.toString(Arrays.copyOf(original,
newLength)));
    }
}

Output:

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



No comments:

Post a Comment