How do you define an array in Java?
In Java, you can define an array using the following syntax:
- Declare the type of array and the name of the array:
dataType[] arrayName;
Or perhaps
dataType arrayName[];
- fresh
arrayName = new dataType[arrayLength];
- When creating an array, you can directly initialize the elements.
dataType[] arrayName = {element1, element2, element3, ...};
Or alternately
dataType[] arrayName = new dataType[]{element1, element2, element3, ...};
For example, the following is an example of defining an integer array:
int[] numbers;
numbers = new int[5];
int[] numbers = {1, 2, 3, 4, 5};
int[] numbers = new int[]{1, 2, 3, 4, 5};
It should be noted that the index of an array starts at 0, meaning the index of the first element is 0, the index of the second element is 1, and so forth.