How to initialize an array in Java?
There are several ways to initialize an array in Java. Here are some examples:
- Using the
newoperator:
int[] array = new int[10];This creates an array of 10 integers with default values of 0.
- Using an array literal:
int[] array = {1, 2, 3, 4, 5};This creates an array with the specified values.
- Using the
fill()method:
int[] array = new int[10];
Arrays.fill(array, 0);This creates an array of 10 integers with all elements set to the specified value (in this case, 0).
- Using a loop:
int[] array = new int[10];
for (int i = 0; i < array.length; i++) {
array[i] = i;
}This creates an array of 10 integers with the elements set to their index values (i.e. array[0] = 0, array[1] = 1, etc.).
Note that in all of these examples, the array is being initialized with a fixed size. If you need to initialize an array with a variable number of elements, you can use an ArrayList instead. An ArrayList is a resizable array that allows you to add and remove elements as needed.