How to define and initialize an array in Java?

In Java, you can define and initialize an array using the following methods:

  1. Declare an array and specify its size, then assign values one by one.
int[] numbers = new int[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
  1. Declare an array and initialize it immediately.
int[] numbers = {10, 20, 30, 40, 50};
  1. Initialize an array using a loop structure.
int[] numbers = new int[5];
for (int i = 0; i < numbers.length; i++) {
    numbers[i] = (i + 1) * 10;
}
  1. Definition and initialization of a two-dimensional array:
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

It is important to note that array indexes start at 0, so be mindful of the index range when assigning and accessing array elements.

bannerAds