How to create an array in Java?

In Java, arrays can be created using the following methods:

  1. Declare an array variable, specifying the type and name of the array, but do not allocate memory space.
  2. Array name of type data type;
  3. Allocate memory space using the keyword “new” and specify the size of the array.
  4. Array name = new data type[array size];
  5. Allocate memory space while declaring the array.
  6. Array of data type[] arrayName = new data type[arraySize];
  7. You can use curly braces {} to initialize the elements of an array.
  8. Array of data type [] array name = {element1, element2, …};
  9. It is possible to initialize the elements of the array step by step.
  10. Array data_type[] arrayName = new data_type[arraySize];
    arrayName[index] = value;

Here are some sample codes:

int[] numbers; // 声明一个整数数组变量
numbers = new int[5]; // 分配一个包含5个元素的整数数组

int[] numbers2 = new int[3]; // 声明并分配一个包含3个元素的整数数组

String[] names = {"Alice", "Bob", "Charlie"}; // 声明一个字符串数组,并初始化元素

double[] grades = new double[4]; // 声明并分配一个包含4个元素的双精度浮点数数组
grades[0] = 90.5; // 初始化数组元素
grades[1] = 85.0;
grades[2] = 78.5;
grades[3] = 92.0;

Please be aware that in Java, array indexes start from 0, so when accessing array elements, the index ranges from 0 to the length of the array minus 1.

bannerAds