Home >Java >javaTutorial >How to Correctly Initialize and Access Elements in a Java Array?

How to Correctly Initialize and Access Elements in a Java Array?

Barbara Streisand
Barbara StreisandOriginal
2024-12-26 02:52:12601browse

How to Correctly Initialize and Access Elements in a Java Array?

Array Initialization in Java

When attempting to initialize an array as shown below:

int data[] = new int[10]; 
public Array() {
    data[10] = {10,20,30,40,50,60,71,80,90,91};
}

Java compilation may encounter an error. The root of the problem lies in the array initialization line:

data[10] = {10,20,30,40,50,60,71,80,90,91};

This line incorrectly assigns an array to data[10], which can only hold a single element. To correctly initialize an array, two approaches can be considered:

Array Initializer:

int[] data = {10,20,30,40,50,60,71,80,90,91};

In this approach, the array is initialized directly during its declaration.

Manual Initialization:

int[] data;
data = new int[] {10,20,30,40,50,60,71,80,90,91};

Here, the array is first declared, and then a new array is assigned to it using the new keyword.

Note that the correction of the syntax does not resolve all issues. Accessing data[10] remains incorrect in the provided code, as Java arrays have 0-based indices. Attempting to access an element beyond the valid range (from 0 to 9) will throw an ArrayIndexOutOfBoundsException.

The above is the detailed content of How to Correctly Initialize and Access Elements in a Java Array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn