×

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays.

Syntax:

Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )  

Parameters:

  • The array to be filled is specified by the arr argument.
  • The formIndex argument specifies the index of the first element that will be filled with the value specified.
  • The toIndex option specifies the index of the most recently filled index with the specified value.
  • The val option specifies the value to be placed in all array elements.

ArrayFillEx.java:

// importing packages and the methods required  
import java.io.*;
import java.util.Arrays;  
import java.util.Scanner;    
// create ArrayFillEx 
public class ArrayFillEx 
{  
  
    public static void main (String [] args)  
    {  
        int arraysize, fillele;    
        Scanner sc = new Scanner (System.in);    
        System.out.print (" arraysize-size of the array: ");    
        arraysize = sc.nextInt ();    
        //creates an array of arraysize 100  
        Int [] arrfill = new int [100];    
        System.out.println (" enter elements into  the array : ");    
        for (int i = 0; i < arraysize; i++)    
        {    
            arrfill [i] = sc.nextInt ();    
        }  
        System.out.print (" element  to be filled into  the array: ");    
        fillele = sc.nextInt ();  
        // filling complete array with fillele  
        Arrays.fill (arrfill, fillele);  
          
        System.out.println ("After filling " +fillele+ " in the array:\n" + Arrays.toString (arrfill));  
    }  
}  

Output:

Java Arrays Fill

ArrayFillEx1.java:

// import packages 
import java.util.Arrays;  
import java.util.Scanner;    


public class ArrayFillEx1
{  
    
    public static void main(String[] args)  
    {  
        int arraysize, fillele, ind1, ind2;    
        Scanner sc = new Scanner(System.in);    
        System.out.print("please enter the number for the size of array: ");    
        arraysize = sc.nextInt();    
        
        int[] arrfill = new int[100];    
        System.out.println("please enter the elements to be filled in the array: ");    
        for(int i = 0; i < arraysize; i++)    
        {    
            arrfill[i] = sc.nextInt();    
        }  
        System.out.print("please enter the element that you want to fill into array: ");    
        fillele = sc.nextInt();  
    System.out.print("please enter the index from which you want to start the fill "+fillele+" in the array: ");    
        ind1 = sc.nextInt();  
        System.out.print("Please enter the index till which ind you want to fill "+fillele+" in the array: ");    
        ind2 = sc.nextInt();  
        
        Arrays.fill(arrfill, ind1, ind2, fillele);  
          
        System.out.println("After filling" +fillele+ " to the array:\n" + Arrays.toString(arrfill));  
    }  
}  

Output :

Java Arrays Fill

2-D Array Fill :

We may use the Arrays.fill() function to fill the multidimensional array in the same way that we would a single-dimensional array. To fill a multidimensional array, we utilise the for loop, which fills each row of the array.

Let's look at an example to see how we can use the Arrays.fill() function to fill a multidimensional array.

ArrayFillEx1.java

// import required classes and packages  
import java.io.*;
import java.util.Arrays;  
import java.util.Scanner;    
// create ArrayFillEx1 for multidimensional array  
public class ArrayFillEx1
{  
      
    public static void main(String[] args)  
    {  
  


  
  Scanner sc = new Scanner(System.in);    
        int fillele;    
         
        
        System.out.print("please enter a number for the size of the array: \n");    
        System.out.print("please enter a number for size of row : \n");  
        int r = sc.nextInt();  
        System.out.print("please enter a number for size of column : \n");  
        int c = sc.nextInt();    
         
        int twoDArrfill[][] = new int[r][c];  
        System.out.println("please enter a number for the elements to fill in the array: \n");    
        for(int i = 0; i < r; i++)  
        {              
           for(int j = 0; j < c; j++)  
           {  
               System.out.println("please enter the elements ["+i+"]["+j+"]");  
               twoDArrfill[i][j] = sc.nextInt();  
           }  
}         
        System.out.print("please enter the element that you wanted to fill in the array: \n\n");    
        fillele = sc.nextInt();  
        System.out.println("Multi-dimensional array after filling withelements: \n\n");    
        System.out.println(Arrays.deepToString(twoDArrfill));  
        
        for (int[] row : twoDArrfill)  
            Arrays.fill(row, fillele);  
        System.out.println("After filling" +fillele+ " in to array:\n\n" + Arrays.deepToString(twoDArrfill));  
        sc.close();  
    }  
}  

Output:

Java Arrays Fill

ArrayFillEx2.java:

// importing required classes and packages  
import java.io.*; 
import java.util.Arrays;  
import java.util.Scanner;    
// create ArrayFillEx2 class  
public class ArrayFillEx2
{  
     
    public static void main (String [] args)  
    {  
        int fillele;    
         
        Scanner sc = new Scanner (System.in);    
        System.out.print ("please enter a number for the size of array: \n");    
        System.out.print ("please enter a value for p : ");  
        int p = sc.nextInt ();  
        System.out.print ("please enter a value for q : ");  
        int q = sc.nextInt ();    
        System.out.print ("please enter a value for r : ");  
        int r = sc.nextInt ();   
        // create 3d array  
        int threeDArrFill [][][] = new int[p][q][r];  
        System.out.println ("please enter the elements to be inserted into the array : ");    
        for (int i=0; i < threeDArrFill.length; i++){  
            for (int j=0; j < threeDArrFill[i].length; j++){  
                for (int k=0; k < threeDArrFill[i][j].length; k++){  
                       System.out.println ("Enter element ["+i+"] ["+j+"] ["+k+"]");  
                       threeDArrFill [i][j][k] = sc.nextInt ();  
                }  
            }  
        }  
        System.out.print ("please enter the element that you wanted to fill in the  3d array: \n\n");    
        fillele = sc.nextInt ();  
        System.out.println ("3D array after filling elements elements: \n\n");    
        System.out.println (Arrays.deepToString(threeDArrFill));  
     
        for (int [][] newArr : threeDArrFill) {  
            for (int [] newRowColumnArr : newArr) {  
                Arrays.fill (newRowColumnArr, fillele);  
            }  
        }  
        System.out.println ("After filling" +fillele+ " in the array:\n\n" + Arrays.deepToString (threeDArrFill));  
        sc.close ();  
    }  
}  

Output:

Java Arrays Fill

Related Topics

Constructor Chaining and Constructor Overloading in Java

Constructor Chaining Constructor chaining and constructor overloading are two confusing terms. Let's first understand constructor chaining.Constructor chaining is the process of calling one constructor from another constructor using the same object....

2 minutes read.

JDK | Java Development Kit

Java Development Kit (JDK) The Java Development Kit is a software development environment used to create Java applications. The JDK includes JRE (Java Runtime Environment), an interpreter (java), a compiler (javac),...

3 minutes read.

Java Pass-by-Reference

In Java, passing parameters can be done using one of two fundamental methods. Pass-by-value is used for the first and pass-by-reference is used for the second. One thing to keep...

2 minutes read.

Java IO

It is a part of java libraries but is often known as I/O streams, file I/O, and file handling. The Java I/O concept satisfies the need for input processing and...

4 minutes read.

Thread Scheduler in java

Scheduling: it is defined as the execution of multiple threads on a single CPU in some order is called scheduling. Preemptive-priority scheduling: This algorithm schedules threads based on their priority relative to other...

11 minutes read.

Convert JSON to Map in Java

JACKSON and GSON libraries are two extremely capable JSON-related libraries offered by Java. To efficiently work with the returned JSON data, we frequently need to convert JSON responses into a...

6 minutes read.

Java Null Keyword

Null is a term that is only used for literal values in Java. Although it appears to be a term, it is a literal opposite of true and false. Java's...

3 minutes read.

Switch Case Program in Java

Switch Case Program in Java The switch case program in Java controls which code snippet gets executed on the basis of the value of the expression mentioned in the switch statement....

22 minutes read.

Java Math log1p() Method

The log1p() method of Math class returns the natural logarithmic sum for the specified double argument and 1. Its value is much closer to result of ln(1 + x). Syntax: public static...

2 minutes read.

Uses of Java

Java is used in many real-world Java applications, including technologies and tools. This Java programming language has become the backbone for developing many applications. In areas like embedded systems and...

3 minutes read.

How to calculate time difference in Java

In this tutorial, we learned about how to calculate time differences in java language and which methods use to find the difference and its example. Prerequisite To understand this example, you need...

5 minutes read.

Java While Loop

A while loop is used to repeatedly execute a set of statements as long as its condition evaluates to true. This loop checks the condition before it starts the execution...

1 minute read.

Least Operator to Express Number in Java

In this article, we will learn about how to obtain a target number using a single number or a single integer by leveraging least operators in Java. There can be...

3 minutes read.

Determine the Upper Bound of a Two-Dimensional Array in Java

Multi-Dimensional Array Multi-faceted exhibits in Java are regular and can be named various clusters. Information in a two-layered bunch in Java is put away in 2D even structure. A two-layered collection...

3 minutes read.

URLConnection class in Java

A communication channel between the URL and the program is represented by the Java URLConnection class. It may be utilized to read from and write to the given resource the...

4 minutes read.

StringBuffer in Java

StringBuffer in Java Similar to StringBuilder, the Java StringBuffer class is also used to create modifiable or mutable strings. The StringBuilder class is synchronized, i.e., thread-safe. Java StringBuffer ConstructorThe StringBuffer class has...

7 minutes read.

Java Package Keyword

A collection of classes, interfaces, and subpackages in a Java program are referred to as a package. Here, we'll learn in-depth how to make and use user-defined packages. package is a...

6 minutes read.

CopyOnWriteArrayList in Java

The CopyOnWriteArrayList is used to implement the List Interface. It is the improved version of ArrayList. The operations like add, remove, set, update etc, these operations are done by creating...

5 minutes read.

Java Integer max() method

The max() method of Integer class returns the greater of two int values. It returns the same result as by calling Math.max. Syntax public static int max(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Race Condition in Java

Java is a multi-threaded programming language, race conditions are more likely to arise. Mostly because data can change when multiple threads visit the same resource simultaneously. Race conditions are concurrency...

3 minutes read.