Home >Java >javaTutorial >Why Can't I Initialize a Non-Declared Java Array Directly with Curly Braces?

Why Can't I Initialize a Non-Declared Java Array Directly with Curly Braces?

Linda Hamilton
Linda HamiltonOriginal
2024-12-09 10:24:20439browse

Why Can't I Initialize a Non-Declared Java Array Directly with Curly Braces?

Array Initialization Syntax for Non-Declared Arrays

In Java, initializing arrays presents nuances when the array is not declared simultaneously. While the following syntax is valid:

AClass[] array = {object1, object2};

and this syntax is also acceptable:

AClass[] array = new AClass[2];
...
array[0] = object1;
array[1] = object2;

the following code is not allowed:

AClass[] array;
...
array = {object1, object2};

Reason for the Restriction

The reason for this restriction remains a mystery, possibly due to underlying grammatical reasons. It was not present in Java 1.0 but was introduced in later versions.

Workaround

One workaround is to use this syntax:

AClass[] array;
...
array = new AClass[]{object1, object2};

The above is the detailed content of Why Can't I Initialize a Non-Declared Java Array Directly with Curly Braces?. 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