Arrays.copyOf(float[], int): This method is available in java.util.Arrays class of Java.
Syntax:
float[] java.util.Arrays.copyOf(float[] original, int newLength)
This method takes two arguments one of type float 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 ArrayscopyOffloat {public static void main(String[] args) {float original[] = { 1, 2, 10, 5 };int newLength = 3;System.out.println(Arrays.toString(Arrays.copyOf(original,newLength)));}}
Output:
[1.0, 2.0, 10.0]
Approach 2: NegativeArraySizeException
Java
import java.util.Arrays;public class ArrayscopyOffloat {public static void main(String[] args) {float 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:3656)
Approach 3: NullPointerException
Java
import java.util.Arrays;public class ArrayscopyOffloat {public static void main(String[] args) {float 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:3657)
No comments:
Post a Comment