Low Orbit Flux Logo 2 D

Java How To Fill An Array

In the Java programming language it is easy to fill or populate an array. You can do this with the fill() method, a for loop, or during initialization.

Answer: To fill an array in Java use one of the following methods:

You can fill a new or existing array using the fill() method like this:

int[] a = new int[5];
Arrays.fill(a, 2);       // [2, 2, 2, 2, 2]

Java Fill an Array with The fill() Method

Here is a more complete example. Remember to import java.util.*;

import java.util.*;
  
class Test1 {
    public static void main( String args[] ) {
        int[] a = new int[5];
        Arrays.fill(a, 2);       // [2, 2, 2, 2, 2]

        System.out.print("[");
        for (int i: a) {
                System.out.print(i + ", ");
        }
        System.out.println("]");
    }
}

Populate an Array with a For Loop

You can also populate an array in Java with a for loop like this:

import java.util.*;
  

class Test1 {
    public static void main( String args[] ) {
        int[] a = new int[5];

        for (int c = 0; c < a.length; c++ ) {
                a[c] = 3;
        }
    }
}

Just Initialize It

You can also initialize an array with the values that you want at the time of declaration. This is less practical with larger arrays.

int[] a = new int[] {2, 2, 2, 2};

Java - How do You Fill an Array with 0?

Filling an array with zeros in is easy in Java. You can pretty much just use the method that we covered above. Just make sure that you specify the value 0.

int[] a = new int[5];
Arrays.fill(a, 0);       // [0, 0, 0, 0, 0]