Fill Elements in a Float Array in Java



In this article, we will learn how to fill elements in a float array in Java. The Arrays.fill() method is used to assign a specified value to each element of the array.

Array fill() method

The Arrays.fill() method in Java sets all elements of an array to a given value, making it useful for quickly initializing or resetting arrays. The Arrays.fill() method works with various data types like int, char, double, and boolean. It makes it easy to fill arrays with a default or specific value.

Syntax
Arrays.fill(array, value)
Arrays.fill(array, start, end, value)

Steps to fill elements in a float array

Elements can be filled in a float array using the Arrays.fill() method from java.util package. This method assigns the required float value to the float array in Java. The two parameters required are the array name and the value that is to be stored in the array elements.

The following are the steps to fill elements in a float array ?
  • Step 1: Define the float array and value: A float array is created, and a float value is defined that will be used to fill the array.
float[] floatArray = new float[5];
float floatValue = 8.5F;
  • Step 2: Fill the array: The Arrays.fill() method is used to assign the defined value (8.5F) to each element of the array.
Arrays.fill(floatArray, floatValue);
  • Step 3: Print the array content: The array is printed using the Arrays.toString() method to display the contents of the filled array.

System.out.println("The float array content is: " + Arrays.toString(floatArray));

Java program to fill elements in a float array

The following is an example of a Java program to fill elements in a float array ?

import java.util.Arrays;
public class Demo {
	public static void main(String[] argv) throws Exception {
		float[] floatArray = new float[5];
		float floatValue = 8.5F;
		Arrays.fill(floatArray, floatValue);
		System.out.println("The float array content is: " + Arrays.toString(floatArray));
	}
}

Output

The float array content is: [8.5, 8.5, 8.5, 8.5, 8.5]
Updated on: 2025-02-10T11:34:34+05:30

300 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements