Array Access
Array access refers to the process of retrieving or modifying the elements of an array by their index. In Java, arrays are zero-indexed, which means the first element of an array has an index of 0, the second element has an index of 1, and so on.
To access an element in an array, you use the array variable name followed by the index inside square brackets. For example, numbers[0]
would access the first element of the numbers
array.
Here's an example:
1int[] numbers = {1, 2, 3, 4, 5};
2
3// Accessing elements of an array by index
4System.out.println(numbers[0]); // Output: 1
5System.out.println(numbers[2]); // Output: 3
6System.out.println(numbers[4]); // Output: 5
In this example, we have an integer array numbers
with 5 elements. We access the first element using numbers[0]
, the third element using numbers[2]
, and the last element using numbers[4]
.
It's important to note that accessing an element outside the valid index range of an array will result in an ArrayIndexOutOfBoundsException
. For example, if you try to access numbers[5]
in the above example, it would throw an exception since the index 5
is greater than the maximum valid index.
Array access is a fundamental operation when working with arrays. It allows you to retrieve and manipulate individual elements in an array, enabling you to perform various algorithms and operations on the data stored in the array.
xxxxxxxxxx
class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
// Accessing elements of an array by index
System.out.println(numbers[0]); // Output: 1
System.out.println(numbers[2]); // Output: 3
System.out.println(numbers[4]); // Output: 5
}
}