How do I clear the content of an array?

In this example you’ll learn how to clear or reset the content of an array. We can use the java.util.Arrays.fill() method to replace to content of each element in the array. In the example below we create two arrays, names and numbers array. We initialize these arrays with some values and then clear the value by assigning null to each element of the array using the Arrays.fill() method.

package org.kodejava.example.util;

import java.util.Arrays;

public class ArrayClear {
    public static void main(String[] args) {
        String[] names = {"Alice", "Bob", "Carol"};
        System.out.println("names = " + Arrays.toString(names));

        //
        // Replace the contents of the names array to null for each array
        // element.
        //
        Arrays.fill(names, null);
        System.out.println("names = " + Arrays.toString(names));

        Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        System.out.println("numbers = " + Arrays.toString(numbers));
        
        //
        // Replace the contents of the numbers array to null for each
        // array element.
        //
        Arrays.fill(numbers, null);
        System.out.println("numbers = " + Arrays.toString(numbers));
    }
}

The output of the code snippet:

names = [Alice, Bob, Carol]
names = [null, null, null]
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers = [null, null, null, null, null, null, null, null, null, null]
Wayan Saryada

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.
Wayan Saryada

Leave a Reply