[SOLVED] In Java why is this syntax valid and this isn't?

Issue

I understand that both of these are valid and mean the exact same thing:

Preferred:

void foo(int[] bar){
    // do something 
}

Not preferred:

void foo(int bar[]){
    // do something
}

What I don’t understand is, following the same logic as above, why is this not valid?

void foo(int... bar[]){
    // do something 
}

But this is:

void foo(int[]... bar){
    // do something 
}

Solution

Let’s start with int bar[] versus int[] bar. The former is some syntactic sugar included in the original Java 1.0 for programmers transitioning from C or C++. It is a bit of a "wart" on the Java syntax … and most people now think it was a mistake to support it in the first place. And you are discouraged from using it by the spec itself, tutorials, books and … Java style checkers.

So later in the evolution of Java (in Java 5) they added the ... syntax to support "varargs" functionality in method calls. Nice. But they didn’t include support for the syntactic wart.

Why?

  • We weren’t in the room when the decisions were made … so we don’t really know why.
  • Because the original wart was a bad idea
  • Because C / C++ don’t support varargs that way, so it wouldn’t help the transitioners.
  • Because int... bar[] is visually ambiguous1. Is it a "varags of arrays of int" or an "array of varargs of int"? Even C and C++ will not allow you to write int[] bar[], which is roughly what this maps to.
  • Because (frankly) void foo(int... bar[]) looks nasty.

1 – Maybe not actually ambiguous, since the "array of varargs of int" interpretation doesn’t make sense. However, that is not going to avoid the confusion that the hypothetical syntax would cause. Best to avoid the problem … like they did.

Answered By – Stephen C

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.