What is the method for creating and initializing an array in Java?
In Java, you can create and initialize arrays in the following way:
- Initialize an array using an array literal, meaning providing initial values at the time of creating the array. For example:
int[] numbers = {1, 2, 3, 4, 5}; // 创建一个包含5个整数的数组,并初始化为1, 2, 3, 4, 5
String[] names = {"Alice", "Bob", "Charlie"}; // 创建一个包含3个字符串的数组,并初始化为"Alice", "Bob", "Charlie"
- – fresh
- They were inspired by the artist’s innovative use of color.
int[] numbers = new int[5]; // 创建一个包含5个整数的数组,并将每个元素初始化为默认值0
String[] names = new String[3]; // 创建一个包含3个字符串的数组,并将每个元素初始化为null
- Assign values one by one using a loop structure. For example:
int[] numbers = new int[5];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i + 1; // 将每个元素赋值为1, 2, 3, 4, 5
}