java how to fill an array

java how to fill an array

To fill an array in Java with a specific value, you can use the Arrays.fill method of the java.util.Arrays class.

Here is an example of how to fill an array of integers with the value 0:

refer t‮‬o:lautturi.com
import java.util.Arrays;

int[] array = new int[10];
Arrays.fill(array, 0);

In this example, the array variable is declared as an array of integers with a size of 10. The Arrays.fill method is then used to fill the array with the value 0.

You can also use a loop to fill the array with a specific value:

for (int i = 0; i < array.length; i++) {
    array[i] = 0;
}

In this example, a for loop is used to iterate over the elements of the array variable. The loop assigns the value 0 to each element of the array.

You can use a similar approach to fill an array with a specific value of any data type, such as a string or an object.

For example, to fill an array of strings with the value "Hello":

String[] array = new String[10];
Arrays.fill(array, "Hello");

Or, using a loop:

for (int i = 0; i < array.length; i++) {
    array[i] = "Hello";
}

These examples will fill the array variable with the specified value.

Note that the Arrays.fill method is a utility method that can be used to quickly fill an array with a specific value. If you need to fill the array with a more complex value, or if you need to perform additional operations on each element of the array, a loop may be more appropriate.

Created Time:2017-11-03 22:21:13  Author:lautturi