How to create an array in Java
In Java, you can create arrays using the following two methods:
- Create an array using the static initialization syntax. This method is suitable for cases where the values of the array elements are already known. An example code is shown below:
int[] numbers = {1, 2, 3, 4, 5}; // 创建一个包含5个整数的数组,并给数组元素赋值
- Create an array using the dynamic initialization syntax. This method is useful for cases where the values of the array elements need to be determined at runtime. Here is an example code:
int[] numbers = new int[5]; // 创建一个包含5个整数的数组,初始值为0
In the above code, int[] denotes the creation of an array of integer type, numbers is the name of the array, new int[5] signifies the creation of an array containing 5 integers, and assigning it to the variable numbers.