Description

On this document we will be showing a java example on how to use the fill() method of Arrays Class. This method is overloaded in such a way that all possible data type is handled. This method assigns the specified data type value to each element of the specified range of the specified array. There are also methods available which you can specify the star and end index which signifies the insertion point of values.

Method Syntax

public static void equals(datatype[] a, dataype val)

Method Returns

The equals() method returns true if the two arrays are equal.

Compatibility

Requires Java 1.2 and up

Java Arrays fill() Example

Below is a java code demonstrates the use of fill() method of Arrays class. The example presented might be simple however it shows the behavior of the fill() method.

package com.javatutorialhq.java.examples;

import java.util.Arrays;

/*
 * A java example source code to demonstrate
 * the use of fill() method of Arrays class
 */

public class ArraysFillExample {

	public static void main(String[] args) {

		// initialize a new int array
		int[] values = new int[]{
			132,75,45,98
		};
		// fill the array with 0's
		Arrays.fill(values, 0);
		System.out.println(Arrays.toString(values));
		
		// fill with 1 from index 1 to 3
		Arrays.fill(values, 1,3,1);
		System.out.println(Arrays.toString(values));
				
	}
}

The above example demostrates the use of fill(method). Initially we have instantiated a new int array of 4 elements. We use the fill method with the int array and 0 as an argument. Our intention is to put 0 to all elements on our array. The result were printed out which shows that we have now a 4 element array with all elements being 0. Then we use another fill method to put 1’s on our array starting from index 1 until three.

Sample Output

Below is the sample output when you run the above example.

Arrays fill() example output