Java Array Syntax Soup: Syntactic Irregularity and Ad Hoc Logic
Here is a example of Java array.
public class Ar { public static void main(String[] args) { int[] myA; myA = new int[10]; myA[3] = 7; } }
Note the idiocy. The []
is used in multiple places. Each place has different semantics.
In this irregular but convenient syntax: int[] v = {3,4};
, it does several things in one shot: {array type declaration, value assignment, number of elements declaration, slots fulfillment}. However, this syntactical idiosyncrasy cannot be used generally. For example, the following is a syntax error:
int[] v = new int[2]; v = {3, 4};
Here is a complete code you can try.
public class H { public static void main(String[] args) { int[] v = new int[2]; v = {3,4}; System.out.print(v[0]); } }
The compiler error is: “illegal start of expression”.
Note that the following syntax, which seems logical and regular, is not a valid syntax:
int[] myA; // declare myA to be a array of int myA = new int[2]; // give myA a value and declare its length myA[] myB; // declare myB to be another array of “type myA”. (COMPILER ERROR!) myB = new myA[3]; // give myB a value and declare its length
The technical reason that the above gives a compiler error, is because myA isn't a Java datatype.