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

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

Syntax:

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

This method takes two arguments one of type boolean array and the other is of type int as its parameters. This method copies the specified array, truncating or padding with false (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 false elements 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 ArrayscopyOfboolean {
    public static void main(String[] args) {

        boolean original[] = { true, false, false, true };

        int newLength = 3;

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

Output:

[true, false, false]


Approach 2: NegativeArraySizeException 

Java

import java.util.Arrays;

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

        boolean original[] = { true, false, false, true };

        int newLength = -1;

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

Output:

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



Approach 3: NullPointerException 

Java

import java.util.Arrays;

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

        boolean 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:3705)



No comments:

Post a Comment