How to define an array in Java?
In Java, you can define an array using the following syntax:
- Specify the type and name of the array when declaring it, without specifying its size.
- An array of integers named numbers is declared.
- Specify the type, name, and size of an array when declaring it.
- Create an array named numbers that can hold five integer values.
- Initialize array elements directly when declaring the array.
- Create an array of integers with the numbers 1, 2, 3, 4, 5.
In the above examples, int is the type of the array and numbers is the name of the array. In the first example, the size of the array is not specified, so memory allocation needs to be done for the array in subsequent code. In the second example, new int[5] is used to allocate a memory space of size 5 for the array. In the third example, the elements in the array have been initialized to 1, 2, 3, 4, and 5.
Please note that the size of the array must be a non-negative integer, and the indexes of the array start from 0.