How to create an array and add elements in Java?
In Java, you can create an array and add elements by following these steps:
- Declare an array variable: First, you need to declare an array variable to store the array object. The syntax is as follows:
数据类型[] 数组名;
For example, declare a variable of type integer array:
int[] numbers;
- fresh
数组名 = new 数据类型[数组长度];
For example, create an integer array with a length of 5.
numbers = new int[5];
- Add elements: You can access and modify elements in an array using array indexes. Array indexes start at 0 and increase sequentially. The syntax is as follows:
数组名[索引] = 值;
For example, assign the value of 10 to the first element of the array.
numbers[0] = 10;
The complete example code is shown below:
public class Main {
public static void main(String[] args) {
int[] numbers; // 声明数组变量
numbers = new int[5]; // 创建数组对象
numbers[0] = 10; // 添加元素
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
System.out.println("数组元素:");
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}
Output:
数组元素:
10
20
30
40
50
This successfully creates an integer array of length 5 and adds the corresponding elements.