Several ways to define arrays in Java
There are several ways to define arrays in Java.
- Declare and initialize an array:
- arr contains the numbers 1, 2, 3, 4, and 5.
- Allocate and initialize array space using the “new” keyword.
- Create an array ‘arr’ with a length of 5 and assign values 1, 2, 3, 4, and 5 to its elements.
- Declare an array and initialize it using a loop.
- Create an array of integers with a length of 5, then fill the array with values starting from 1 up to the length of the array.
- Initialize an array using the static methods of the Arrays class.
- Initialize an array of integers with a length of 5 and set all elements to 0.
- Initialize an array using array literals.
- Create an array called arr that contains the integers 1, 2, 3, 4, and 5.
Note: In Java, arrays start indexing at 0, so when accessing array elements, the index range is from 0 to the length minus 1.