Home > Java > javaTutorial > How Does Java's Array Assignment Syntax Differ Inside and Outside of Declarations?

How Does Java's Array Assignment Syntax Differ Inside and Outside of Declarations?

Barbara Streisand
Release: 2024-12-30 03:10:13
Original
214 people have browsed it

How Does Java's Array Assignment Syntax Differ Inside and Outside of Declarations?

Array Assignment Syntax Outside of Declarations

Java's array initialization syntax differs depending on whether it's used in a declaration or an assignment.

Initializing with Array Literals

When declaring an array, array literals can be used to initialize its elements:

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

Initializing with the new Operator

Outside a declaration, arrays can be initialized using the new operator, followed by the element count and subsequent assignments:

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

Syntax Restrictions: Assigning Array Literals to Non-Declared Arrays

However, attempting to assign an array literal to a non-declared array variable is prohibited:

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

This restriction is imposed by Java for reasons that may not be immediately apparent.

Workaround: Using new Operator with Array Literals

As a workaround, the following syntax can be used:

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

This approach combines the array creation and initialization into a single statement while adhering to Java's syntax rules.

Example

For example, consider the following code snippet:

public void selectedPointsToMove(cpVect coord) {

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

Without the workaround, the code would require additional statements to initialize tempTab before assigning it to tab.

The above is the detailed content of How Does Java's Array Assignment Syntax Differ Inside and Outside of Declarations?. 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