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 elements of the array.

Let see the following code snippet as an example:

package org.kodejava.example.util;

import java.util.Arrays;

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

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

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

        // Assign 9 to each elements 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 elements of the int, float and String array. To change the default value of multi dimensional array we can’t directly call the Arrays.fill() method. In the example we use for-loop to set each elements 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 Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.

Leave a Reply