About Lesson
n Java, you can access the elements of an array by specifying the index of the element you want to access. Array indexing starts at 0, which means that the first element of an array has an index of 0, the second element has an index of 1, and so on. Here are some examples:
int[] numbers = {1, 2, 3, 4, 5};
int firstNumber = numbers[0]; // access the first element of the array (index 0)
int secondNumber = numbers[1]; // access the second element of the array (index 1)
int thirdNumber = numbers[2]; // access the third element of the array (index 2)
int lastNumber = numbers[4]; // access the last element of the array (index 4)
You can also use variables or expressions as array indices:
java
int[] numbers = {1, 2, 3, 4, 5};
int index = 2;
int thirdNumber = numbers[index]; // access the third element of the array (index 2)
int sum = numbers[1] + numbers[3]; // access the second and fourth elements and calculate their sum
Note that if you try to access an element of an array that doesn’t exist (i.e., an index that is out of bounds), you will get an ArrayIndexOutOfBoundsException
at runtime.
int[] numbers = {1, 2, 3, 4, 5};
int sixthNumber = numbers[5]; // this will cause an ArrayIndexOutOfBoundsException
It’s important to always make sure that your array indices are within the bounds of the array to avoid runtime errors.