Java中ByteArrayOutputStream的toByteArray()[]语法在哪有文档说明?
[] Placement in Java Method Return Types Great question! Let's unpack this syntax you found in ByteArrayOutputStream's source code.
Where is this syntax documented officially?
This is a valid syntax defined in the Java Language Specification (JLS). Specifically, Section 8.4.7 (Method Return Type) clarifies that when declaring a method returning an array type, you can place the square brackets in two equivalent positions:
- After the element type (the more common, widely recommended style:
public synchronized byte[] toByteArray()) - Or after the method identifier (the style you encountered:
public synchronized byte toByteArray()[])
All standard Java compilers recognize both forms as syntactically identical.
Is this consistent with regular array declaration rules?
Absolutely! This is just an extension of the same flexibility you see in variable declarations. For example:
String[] args;(brackets placed after the type)String args[];(brackets placed after the variable name)
These two declarations mean exactly the same thing—args is a reference to a String array. The method return type syntax follows this exact logic: the brackets can be associated with the element type or the method name, with no difference in functionality.
A quick note on your 2018 observation
You mentioned discovering more such special syntax uses later—this pattern applies to method parameters too! For example:
public void processData(int data[]) { /* ... */ }
is completely equivalent to:
public void processData(int[] data) { /* ... */ }
While the style with brackets after the type is favored for readability in most codebases, the compiler accepts both forms without distinction.
内容的提问来源于stack exchange,提问作者smac89

