javajls

What exactly is meant by "any bracket pairs that follow the formal parameter list" in JLS to determine a precise array type in the result of a method?


JLS 17 says the following about determining the array type:

The return type of a method (§8.4.5) may be an array type. The precise array type depends on the bracket pairs that may appear as part of the type at the beginning of the method declaration, or after the method's formal parameter list, or both. The array type is denoted by:

  • the element type that appears in the Result; then,
  • any bracket pairs that follow the formal parameter list; then,
  • any bracket pairs that appear in the Result.

What do formal parameters have anything to do with the result type of a method? Any examples are appreciated.


Solution

  • That section is talking about this valid but extremely very very much NOT recommended style:

    public int[] aMethodThatReturnsAnArrayOfIntArrays() [] {
      return new int[10][20];
    }
    

    Note how there are array brackets after the method's name and the 'formal parameter list' (which is the () - that's the parameter list; this particular example has zero parameters).

    This is identical to:

    public int[][] aMethodThatReturnsAnArrayOfIntArrays() {
      return new int[10][20];
    }
    

    you can always move any array brackets appearing between the ) and { to the end of the return type - it makes no difference to what the method does or means.

    This mirrors how you can pull that stunt with variable declarations:

    int[][] x = new int[10][20];
    for (int y[] : x) { .. }
    
    int[] x[] = new int[10][20], y = new int[30];
    

    ... those forms are also not recommended.

    Why is it legal? Cuz it was in C, and java mostly copied its valid syntax from there.