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

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

Syntax:

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

This method takes two arguments one of type int 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 ArrayscopyOfint {
    public static void main(String[] args) {

        int 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 ArrayscopyOfint {
    public static void main(String[] args) {

        int 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:3584)



Approach 3: NullPointerException 

Java

import java.util.Arrays;

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

        int 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:3585)



No comments:

Post a Comment