How to define arrays in Java
In Java, you can define arrays using the following syntax:
- Initializing an array variable simultaneously with declaration: data type[] array variable name = {element1, element2, …}; For example, defining an integer array and initializing it: int[] numbers = {1, 2, 3, 4, 5};
- Declare an array variable and specify the array length, then assign values to each array element one by one: data type[] array variable name = new data type[array length];
For example, define a string array and specify a length of 3, then assign a value to each element: String[] names = new String[3];
names[0] = “Alice”;
names[1] = “Bob”;
names[2] = “Charlie”; - Declare an array variable and directly specify the length, then use a loop to assign values to the array elements:
Data_Type[] array_variable = new Data_Type[array_length];
for (int i = 0; i < array_length; i++) { array_variable[i] = element_value; } For example, define an integer array and specify a length of 5, then use a loop to assign a value to each element: int[] numbers = new int[5]; for (int i = 0; i < 5; i++) { numbers[i] = i + 1; }
Note: Array indexes start from 0, so the index of the first element is 0.