Several ways to define arrays in Java

There are several ways to define arrays in Java.

  1. Declare and initialize an array:
  2. arr contains the numbers 1, 2, 3, 4, and 5.
  3. Allocate and initialize array space using the “new” keyword.
  4. Create an array ‘arr’ with a length of 5 and assign values 1, 2, 3, 4, and 5 to its elements.
  5. Declare an array and initialize it using a loop.
  6. 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.
  7. Initialize an array using the static methods of the Arrays class.
  8. Initialize an array of integers with a length of 5 and set all elements to 0.
  9. Initialize an array using array literals.
  10. 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.

bannerAds