×

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

Difference between Aggregation and Composition in Java

What is Aggregation? Before we start discussing Aggregation, we have to know some general information about our classes in java. Generally we have two members in our classes , the first...

8 minutes read.

Int vs Integer in Java

In Java, numerical data can be stored using int or Integer. int and Integer both have different definitions but similar usage in Java. What is int in Java? int is a primitive...

4 minutes read.

Reverse a String in Java

Reversing a string means that if we have a string called “what is your name”, the reversed format is “eman ruoy si tahw”. Reversing a string involves totally flipping the...

3 minutes read.

Java String Methods

Java String Methods Java String class is the most important class of the java.lang package. It is used to handle the String related operations. It contains a lot of built-in Java...

2 minutes read.

Java md5 Hash Example

A 128-bit hash value is generated by the Message Digest Algorithm 5, which is a cryptographic algorithm. A stationary hash value is generated by the hash function from data of...

3 minutes read.

Difference between print() and println() in Java

In this tutorial, we will discuss the differences between print and println in Java language. There are mainly two methods to display the text on the console printprintln The above two methods are...

4 minutes read.

Synchronized Keyword in Java

Synchronization is the process of limiting access to a shared resource or data to a single thread at a given moment in time. This aids in shielding the data from...

6 minutes read.

Java Polymorphism

The process of representing one form in multiple forms is known as Polymorphism. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means...

5 minutes read.

Sorting Program in Java

Sorting Program in Java: The sorting program in Java is used to sort arrays either in ascending or descending order.  There are two predefined methods available in Java that are...

6 minutes read.

Differences between Byte Code and Machine Code

This tutorial will discuss the differences between Byte Code and Machine Code. Before that, let's try to know what byte and machine code is. Introduction Every computer has a set of instructions...

4 minutes read.

Balanced Prime Number in Java

This section will cover the definition of a balanced prime number as well as how to find one using a Java program. Balance Prime Number A prime number that is equivalent to...

5 minutes read.

Constructor Overloading in Java

In Java, constructors can be overloaded just like methods. The idea of having multiple constructors with various parameter sets so that each function Object()  can carry out a particular task...

3 minutes read.

Implementing Queue Using Array in Java

We can implement queue by using array in Java. The queue is a linear data structure, and the array is one of the simplest data structures. Before implementing a queue...

4 minutes read.

Arrow Operator in Java

The introduction of arrow functions in ES6 gives you a more precise approach to define JavaScript functions. We can write shorter function syntax thanks to them. Your code will be...

4 minutes read.

Type Annotations in Java

Only declarations were eligible for annotations in earlier versions of Java. With Java 8, you may now annotate any type use, including types in declarations, generics, and casts: @Encrypted String data; List<@NonNull...

6 minutes read.

Bubble Sort in Java

Bubble Sort in Java Bubble sort isalso known as sinking sort. It is one of the simplest sorting algorithms. In the bubble sort algorithm, the given array is traversed from left...

5 minutes read.

Java Linters

When it comes to programming, everyone makes mistakes. Errors are bad for developers since they are difficult to handle. But handling as many as possible errors will bring out the...

6 minutes read.

MOOD Factors to Assess a Java Program

In this tutorial, we will comprehendthe meaning of mood factors in Java. For the development of any software system,the quality of anapplication is important. It is more important to maintain large-scale...

4 minutes read.

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

3 minutes read.

Object class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM mostly generally...

6 minutes read.