Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do square brackets in Java method declarations mean?

The grammar for method declarations in Java is something like the following:

Java method declaration BNF:

method_declaration 
    ::= 
    { modifier } type identifier 
    "(" [ parameter_list ] ")" { "[" "]" } 
    ( statement_block | ";" ) 

And I am wondering what do the square brackets mean.

  1. Can anyone give me an example?
  2. Is method declarations in Java looks like above (What about generics)?
  3. Where can I find complete and actual BNF grammar for Java?
like image 441
midas Avatar asked Dec 26 '22 07:12

midas


2 Answers

The square brackets are to indicate the method returns an array. For example, you can write a method that returns an array of int as:

int method()[] { … }

Many people aren't familiar with this syntax though, and it's best avoided.

You'll find the complete syntax for java 7 here: http://docs.oracle.com/javase/specs/jls/se7/html/jls-18.html

like image 152
Joni Avatar answered Jan 09 '23 05:01

Joni


It is a legacy construct. From the JLS (§8.4. Method Declarations):

For compatibility with older versions of the Java SE platform, the declaration of a method that returns an array is allowed to place (some or all of) the empty bracket pairs that form the declaration of the array type after the formal parameter list. This is supported by the following obsolescent production, but should not be used in new code.

MethodDeclarator:
     MethodDeclarator [ ]

Thus, it is valid Java (even though I've never seen this construct used in real code).

As to the grammar you quote, it seems incomplete. For example, it doesn't seem to include the optional throws clause. Also, it only allows a single pair of square brackets in method_declaration whereas the official grammar allows any number of such pairs.

The definitive reference is the Java Language Specification, Chapter 18. Syntax.

like image 24
NPE Avatar answered Jan 09 '23 06:01

NPE