Java Arrays: Define & Use Guide

In Java, an array is a special type of data structure that can store multiple elements of the same type. To define an array, you can use the following syntax:

// 定义一个整型数组
int[] numbers = new int[5];

The above code defines an array containing 5 integers. To assign values to the array, you can use the following syntax:

numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
numbers[4] = 5;

To access elements in an array, you can use the following syntax:

int value = numbers[2]; // value 等于数组中下标为2的元素的值,即3

In addition, Java also provides a more concise way to define and initialize arrays:

int[] numbers = {1, 2, 3, 4, 5};

In this scenario, the length of the array will be automatically determined based on the number of elements provided during initialization. Elements in the array can still be accessed using the syntax numbers[index].

It is important to note that array indexes start from 0. This means that if an array has a length of 5, the valid index range is from 0 to 4. Attempting to access an index that does not exist in the array will result in an ArrayIndexOutOfBoundsException.

bannerAds