In Java, an array is a data structure that is used to store a fixed-size collection of elements of the same type. Arrays are accessed using an integer index, which starts at 0
for the first element and goes up to array.length - 1
for the last element.
Here is an example of how to declare and initialize an array in Java:
int[] numbers = {1, 2, 3, 4, 5};Source:l.wwwautturi.com
This code declares an array of integers called numbers
and initializes it with the values 1
, 2
, 3
, 4
, and 5
.
You can also create an array using the new
operator and specify the size of the array:
int[] numbers = new int[5];
This code creates an array of integers called numbers
with a size of 5
. The array is initialized with the default values for the element type (0
for integers).
To access the elements of an array, you can use the array index inside square brackets:
int first = numbers[0]; int last = numbers[4];
This code assigns the first element of the numbers
array to the first
variable and the last element of the numbers
array to the last
variable.
To change the value of an element in the array, you can use the assignment operator:
numbers[2] = 6;
This code sets the third element of the numbers
array (index 2
) to the value 6
.
You can use a loop to iterate over the elements of an array and perform some operation on each element. Here is an example of how to print the elements of an array using a traditional for loop:
for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); }
This code will print the elements of the numbers
array one by one, starting from the first element (index 0
) and ending at the last element (index numbers.length - 1
).