DEV Community

Lalit Kumar
Lalit Kumar

Posted on

How to set all values in an array to 0

In this article, I am going to explain how to set all values in an array to zero in java. This operation can be performed by using Arrays.fill() method which assigns the given value to each and every element in the array.

title: "How to set all values in an array to 0"
tags: java

canonical_url: https://kodlogs.com/blog/2611/how-to-set-all-values-in-an-array-to-0

Approach

Arrays.fill() method basically belongs to the known arrays package and is written as java.util.Arrays;

Import this package in order to perform the above-said operation. You can even specify the range or the sub-array region to set it to a particular value.

If you do not know about this method, then you may simply assign that particular array to value 0. But if you need only a particular set of regions to be so, then use the Arrays.fill() method.

The below example explains that on the usage of the method Arrays.fill(array, value) changes each and every element to its value.

Program

import java.util.Arrays;
public class Demo

{

public static void main(String[ ] args)

{

int arr [10] = {0}; 

System.out.println(arr);

int array[ ] = { 1,2, 3, 4, 5, 6, 7, 8, 9, 10};

System.out.println(array);

Arrays.fill(array, 0);

System.out.println(Arrays.toStrin(array));

Arrays.fill(array, 1,4,0); 

System.out.println(Arrays.toStrin(array));

}

}
Enter fullscreen mode Exit fullscreen mode

Output

`
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

[1,2, 3, 4, 5, 6, 7, 8, 9, 10]

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

[1, 0, 0, 0, 5, 6, 7, 8, 9, 10]
`

Top comments (0)