Johannes Schaub - litb Johannes Schaub - litb - 1 year ago 95
Java Question

Weird "[]" after Java method signature

I looked at some Java code today, and I found some weird syntax:

public class Sample {
public int get()[] {
return new int[]{1, 2, 3};

I thought that can't compile and wanted to fix what I thought was a typo, but then I remembered the Java compiler did actually accept it!

Can someone please help me understand what it means? Is it an array of functions?

Answer Source

It's a method that returns an int[].

Java Language Specification (8.4 Method Declarations)

For compatibility with older versions of the Java platform, a declaration form for 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 parameter list.

This is supported by the obsolescent production:

    MethodDeclarator [ ]

but should not be used in new code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download