Arrays.copyOf(char[], int): This method is available in java.util.Arrays class of Java.
Syntax:
char[] java.util.Arrays.copyOf(char[] original, int newLength)
This method takes two arguments one of type char array and the other of type int as its parameters. This method copies the specified array, truncating or padding with null characters (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 null characters 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 ArrayscopyOfchar {public static void main(String[] args) {char orininal[] = { 'a', 'b', 'c', 'd' };int newLength = 5;System.out.println(Arrays.copyOf(orininal,newLength));}}
Output:
abcd
Approach 2: NegativeArraySizeException
Java
import java.util.Arrays;public class ArrayscopyOfchar {public static void main(String[] args) {char orininal[] = { 'a', 'b', 'c', 'd' };int newLength = -6;System.out.println(Arrays.copyOf(orininal,newLength));}}
Output:
Exception in thread "main" java.lang.NegativeArraySizeException: -6 at java.base/java.util.Arrays.copyOf(Arrays.java:3632)
Approach 3: NullPointerException
Java
import java.util.Arrays;public class ArrayscopyOfchar {public static void main(String[] args) {char orininal[] = null;int newLength = 5;System.out.println(Arrays.copyOf(orininal,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:3633)
No comments:
Post a Comment