How do I fill array with non-default value?

This code snippet will show you how to create array variable and initialized it with a non-default value. By default, when we create an array of something in Java all entries will have its default value. For primitive types like int, long, float the default value are zero (0 or 0.0). For reference types (anything that holds an object in it) will have null as the default value. For boolean variable it will be false.

If you want to initialize the array to different value you can use the Arrays.fill() method. This method will help you to set the value for every element of the array.

Let see the following code snippet as an example:

package org.kodejava.util;

import java.util.Arrays;

public class ArraysFillExample {
    public static void main(String[] args) {
        // Assign -1 to each element of numbers arrays
        int[] numbers = new int[5];
        Arrays.fill(numbers, -1);
        System.out.println("Numbers: " + Arrays.toString(numbers));

        // Assign 1.0f to each element of prices arrays
        float[] prices = new float[5];
        Arrays.fill(prices, 1.0f);
        System.out.println("Prices : " + Arrays.toString(prices));

        // Assign empty string to each element of words arrays
        String[] words = new String[5];
        Arrays.fill(words, "");
        System.out.println("Words  : " + Arrays.toString(words));

        // Assign 9 to each element of the multi array
        int[][] multi = new int[3][3];
        for (int[] array : multi) {
            Arrays.fill(array, 9);
        }
        System.out.println("Multi  : " + Arrays.deepToString(multi));
    }
}

In the code snippet above we utilize the Arrays.fill() utility method to assign value for each element of the int, float and String array. To change the default value of multidimensional array we can’t directly call the Arrays.fill() method. In the example we use for-loop to set each element of the sub-array using the Arrays.fill() method.

The output of the code snippet above are:

Numbers: [-1, -1, -1, -1, -1]
Prices : [1.0, 1.0, 1.0, 1.0, 1.0]
Words  : [, , , , ]
Multi  : [[9, 9, 9], [9, 9, 9], [9, 9, 9]]
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.