How to Access Java Array Elements

In Java, accessing elements in an array by index is done by using square brackets [] followed by the corresponding index. The index of an array starts from 0, meaning the first element has an index of 0, the second element has an index of 1, and so on.

Here are examples of how to access array elements:

int[] array = {10, 20, 30, 40, 50};
int element = array[2]; // 获取索引为 2 的元素,即第三个元素(值为 30)
System.out.println(element); // 输出结果为 30

In the example above, we defined an integer array called ‘array’, accessed the element at index 2 using ‘array[2]’, assigned it to a variable called ‘element’, and finally printed out the value of this element.

Remember to make sure the index values are within the legal range when accessing elements using array indexes, to avoid encountering ArrayIndexOutOfBoundsException errors.

bannerAds