24

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

smac89
  • 39,374
  • 15
  • 132
  • 179
  • That is funny. You are talking about the [OpenJDK version](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/io/ByteArrayOutputStream.java#ByteArrayOutputStream.toByteArray%28%29), right? The Oracle version differs here, having the `[]` after the return type, not after the method name. – Turing85 May 03 '18 at 19:57
  • In Java the array goes with the typename, since the resulting object is an array type. So it should be `String[] args`. The 2nd way (like in C language) also works but is discouraged. – Hitobat May 03 '18 at 19:58
  • @Turing85, I'm using oraclejdk not open jdk – smac89 May 03 '18 at 20:01
  • @smac89 Java 8 or prior huh? Seems they "fixed" it in Java 9+ – Turing85 May 03 '18 at 20:05
  • @Turing85 Yes this is Java 8 – smac89 May 03 '18 at 20:08

1 Answers1

31

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.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243