Initialize an array with same values in Java – Multiple ways

In this tutorial, we will learn how to initialize an array with the same values in Java. An array, in Java, is an object of a similar data type that will contain data elements in a contiguous memory location ( an object of a dynamically generated class). Array in Java is a data structure where we can store only a fixed set of data elements of a similar type. Like C/C++, in java also the first element in the array is also stored at index 0.

There are many ways through which we can initialize the array with the same values. They are:

  1. Direct Initialization
  2. for-loop
  3. Arrays.fill()
  4. Arrays,setAll()

Ways to initialize an array with the same values

1)Direct initialization: We can assign the values to the array at the time of declaration. This is the most general one.

In this way:

int arr[]={1,1,1,1,1};

This will initialize the array arr with the values provided i.e. 1.

The complete code:

import java. util.*;
 
public class Main
{
    public static void main(String args[]) throws Exception
    {
        int array[] = { 1, 1,1,1,1};
        for (int i = 0; i < array.length; i++)
        {
            System.out.print(array[i] + " ");
        }
   }
}

The output:

1 1 1 1 1

2) for loop: We can also assign the data elements at every index in the array using for loop. The for loop will iterate over the empty array created dynamically and then place the values at every index. Here we will use the new keyword for dynamically creating the array.

Like this way:

int arr[]=new int[n];

This will create an array dynamically in which we will assign the values.

 for(int i=0;i<n;i++)
{
   arr[i]=in.nextInt();
}

The complete code with user input using Scanner class:

import java.util.*;
public class Main
{
public static void main(String[] args) {

Scanner in = new Scanner(System.in);
int n;
System.out.println("Enter the no of elements");
n=in.nextInt();
int arr[]=new int[n];
System.out.println("Enter the elements in the array");
for(int i=0;i<n;i++)
{
arr[i]=in.nextInt();
}
System.out.println("The elements in the array are:");
for(int i=0;i<n;i++)
{
System.out.print(arr[i]+" ");
}
}
}

Output:

Enter the no of elements
5
Enter the elements in the array 
1 1 1 1 1 
The elements in the array are: 
1 1 1 1 1

3) Arrays.fill(): We can also use this method to assign the data elements of the same data type to the specified array of the specified range.

Here, we will provide only one value and it gets copied to every location in the array.

Like this way:

Arrays.fill(arr, m);

In this, arr is the name of the array and m is the value that is assigned to every location in the array.

The complete code:

import java.util.*;
 
public class Main 
{
     
    public static void main(String args[])
    {
         Scanner in = new Scanner(System.in);
         int n; 
         System.out.println("Enter the no of elements");
         n=in.nextInt();
        int arr[] = new int[n];
        int m;
        System.out.println("Enter the elements"); 
        m=in.nextInt();
        Arrays.fill(arr, m);
        System.out.println("Array completely " + Arrays.toString(array));
   }
}

In the above code, we have assigned the data m to every index of the array arr of specified range using Arrays.fill().

The output of the above code:

Enter the no of elements
5
Enter the elements
12
The array is: 
[12, 12, 12, 12, 12]

4) Arrays.setAll(): We can also assign the data element to the specified array using this method. This function itself can compute the elements to be stored or assigned to the array. Here, we will basically use a ternary operator for the task.

Like this way:

Arrays.setAll(array, p -> p<n? m : null);

In the ternary operator, we will provide the conditions that till the iterator p reaches the limit of the array store a particular value at every index otherwise store null.

The complete code:

import java.util.*;
 
public class Main {

public static void main(String args[]) {

    Scanner in=new Scanner(System.in);
    int n;
    System.out.println("Enter the number of elements");
    n=in.nextInt();
    int[] array = new int[n];
     int m;
    System.out.println("Enter the value");
    m=in.nextInt();
     
    // Setting the value in the array
    Arrays.setAll(array, p -> p<n? m : null);
     
    // Printing the array
    System.out.println("Array completely filled: \n"
                            + Arrays.toString(array));
    }
    
}

The output :

Enter the number of elements
10
Enter the value
12
Array completely filled: 
[12, 12, 12, 12, 12, 12, 12, 12, 12, 12]

Hope this tutorial was useful.

Also read: Swap two elements in an array in Java

Leave a Reply

Your email address will not be published.