Java Array Syntax Soup: Syntactic Irregularity and Ad Hoc Logic

By Xah Lee. Date: . Last updated: .

Here is a example of Java array.

public class Ar {
    public static void main(String[] args) {
        int[] xx;
        xx = new int[10];
        xx[3] = 7;
    }
}

Note the idiocy. The [] is used in 3 places in the class body and each place has different semantics.

You can use this shortcut syntax int[] xx = {3,7,4}; to declare and initialize array at the same time

// example of array
public class Aj {
    public static void main(String[] args) {
        int[] xx = {3,7,4};
        for (int i = 0; i < xx.length; i++) {
            System.out.print(xx[i] + " ");
        } // prints 3 7 4
    }
}

In this irregular but convenient syntax: int[] xx = {3,7,4}; , it does several things in one shot:

However, this syntactical idiosyncrasy cannot be used generally. For example, the following is a syntax error:

 int[] xx = new int[2];
 xx = {3, 4};

Here is a complete code you can try.

public class H {
    public static void main(String[] args) {
        int[] xx = new int[2];
        // compiler error: illegal start of expression
        xx = {3,4};
        System.out.print(xx[0]);
    }
}

Note that the following syntax, which seems logical and regular, is not a valid syntax:

// valid syntax

// declare xx to be a array of int
int[] xx;
// give xx a value and declare its length
xx = new int[2];

// ---------------------
// invalid syntax

// declare yy to be array of type xx.
xx[] yy; // COMPILER ERROR!

// give yy a value and declare its length
yy = new xx[3];

The technical reason that the above gives a compiler error, is because xx isn't a Java datatype.