Arrays.fill(Object[], Object): This method is available in java.util.Arrays class of Java.
Syntax:
void java.util.Arrays.fill(Object[] a, Object val)
This method takes two arguments one of type Object (like Integer, Double, etc) array and the other one of type Object as its parameters. This method assigns the specified Object reference to each element of the specified array of Objects.
Parameters: Two parameters are required for this method.
a: the array to be filled.
val: the value to be stored in all elements of the array.
Returns: NA
Throws:
1. ArrayStoreException - if the specified value is not of a runtime type that can be stored in the specified array.
Approach 1: When no exceptions
Java
import java.util.Arrays;public class Arraysfillobject {public static void main(String[] args) {// Object of type IntegerInteger a[] = new Integer[5];int val = 1;Arrays.fill(a, val);System.out.println(Arrays.toString(a));}}
Output:
[1, 1, 1, 1, 1]
Approach 2: ArrayStoreException
Java
import java.util.Arrays;public class Arraysfillobject {public static void main(String[] args) {// Object of type IntegerInteger a[] = new Integer[5];char val = 'a';Arrays.fill(a, val);System.out.println(Arrays.toString(a));}}
Output:
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Character at java.base/java.util.Arrays.fill(Arrays.java:3429)
No comments:
Post a Comment