Why do Java array declarations use curly brackets? Why do Java array declarations use curly brackets? arrays arrays

Why do Java array declarations use curly brackets?


Curly brackets usually denotes sets and ensembles while parenthesis usually denotes parameters in C-like languages.

A long time ago, people got used to having this kind of convention with C. I'm pretty sure that it works this way in Java to keep some kind of syntax consistency with older languages.


I can't say why James Gosling et al chose this particular alternative ...

However, using round brackets instead of curly brackets would create a serious ambiguity problem for the Java grammar. Consider the following example:

Object[] tableHeaders = ("Cars");

Do the round brackets denote an array constructor, or are they part of the normal expression expression syntax?

Now it would be possible to come up with some complicated precedence rules to cover this, but that makes life difficult for both programmers and compiler writers.

(At the grammatical level, a Java parser needs to deal with ambiguity in:

VariableInitializer:    ArrayInitializer    Expression

In the example above, ("Cars") matches both the ArrayInitializer and Expression productions ... if you use round brackets for array initializers. Deciding which is correct meaning would require looking at the declared variable type ... followed by context sensitive parsing of the VariableInitializer. Nasty.)

I'd say they made the right choice in not using round brackets for array initializers.


Square brackets won't work either. Consider trying to explain this ...

... = new Object[]["Cars"];  // 1-D array

versus

... = new Object[21][];      // 2-D array

versus

... = new Object[][];        // is that 1-D or 2-D?


In most Algol-based programming languages, which are the most widely-used languages, arrays are declared using the curly braces.