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
Release: 2024-12-09 10:24:20
Original
382 people have browsed it

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};
Copy after login

and this syntax is also acceptable:

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

the following code is not allowed:

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

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};
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template