Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java function definition with brackets syntax [duplicate]

Tags:

Was looking in the source for ByteArrayOutputStream, and I saw this function:

public synchronized byte toByteArray()[] {     return Arrays.copyOf(buf, count); } 

Where is this syntax documented? I mean the [] in front of the function. Is this the same as in declaring a regular array where the bracket can go after the name of the array or before, but in this case, the bracket can go after the function name?

String[] args; 

Vs

String args[]; 

Edit: 2018-05-22

I found even more uses of this crazy syntax here: 10 things you didn't know about Java

#3 is where they make mention of all the ways the above syntax can be exploited

like image 909
smac89 Avatar asked May 03 '18 19:05

smac89


People also ask

How do you use brackets in Java?

In Java, brackets are used for the following purposes: Round brackets () Arguments of methods are placed between round brackets. Furthermore, round brackets are used in mathematical formulas to specify priorities of operations, and in control structures such as for-loops and if-clauses.

What do the brackets after a function do?

In JavaScript, the functions wrapped with parenthesis are called “Immediately Invoked Function Expressions" or "Self Executing Functions. The purpose of wrapping is to namespace and control the visibility of member functions. It wraps code inside a function scope and decrease clashing with other libraries.


1 Answers

In JLS Sec 8.4:

MethodDeclarator:     Identifier ( [FormalParameterList] ) [Dims] 

...

The declaration of a method that returns an array is allowed to place some or all of the bracket pairs that denote the array type after the formal parameter list. This syntax is supported for compatibility with early versions of the Java programming language. It is very strongly recommended that this syntax is not used in new code.

like image 153
Andy Turner Avatar answered Oct 04 '22 20:10

Andy Turner