What do square brackets in Java method declarations mean?

放肆的年华 提交于 2019-12-19 03:45:14

问题


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?

回答1:


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




回答2:


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.




回答3:


{ ... } stands for 0..* (zero times or more)

The generics are missing because the document you linked is 17 years old.

The official Java Language Specification uses this particular syntax: http://docs.oracle.com/javase/specs/jls/se7/html/jls-2.html#jls-2.4

I wasn't able to find a real BNF grammar for Java which is less obsolete than yours.




回答4:


Brackets are used for return types being arrays, for example :

Sting myMethodThatRetrunsStringArray[] {
//Implementation
// return a String array
}



回答5:


we say that the } token is to the right of the { token, even though it appears, in this two-dimensional representation, downward and to the left of the { token. This convention about the use of the words left and right allows us to speak, for example, of the right-hand operand of a binary operator or of the left-hand side of an assignment.

http://docs.oracle.com/javase/specs/jls/se7/html/jls-2.html

http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html



来源:https://stackoverflow.com/questions/15585503/what-do-square-brackets-in-java-method-declarations-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!