Home > Java > javaTutorial > Why Does Java Prevent Uninitialized Array Assignment with Curly Braces?

Why Does Java Prevent Uninitialized Array Assignment with Curly Braces?

Patricia Arquette
Release: 2024-12-10 10:16:11
Original
450 people have browsed it

Why Does Java Prevent Uninitialized Array Assignment with Curly Braces?

Uninitialized Array Assignment Syntax

Java allows for concise initialization of arrays within declarations:

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

However, attempting to assign an uninitialized array with curly braces results in a compiler error:

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

Reason for Restriction

The specific reason for this restriction is unclear. It may be due to grammatical complexities or the desire to maintain consistency in Java's syntax.

Workaround

Although not as concise, you can initialize an uninitialized array with the new operator and then assign elements explicitly:

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

Simplified Example

Using this workaround in the provided code snippet simplifies the array initialization logic:

public void selectedPointsToMove(cpVect coord) {

    if (tab == null) {
        if (arePointsClose(coord, point1, 10))
            tab = new cpVect[]{point1};
        else if (arePointsClose(point2, coord, 10))
            tab = new cpVect[]{point2};
        else
            tab = new cpVect[]{point1, point2};
    }
}
Copy after login

The above is the detailed content of Why Does Java Prevent Uninitialized Array Assignment 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