0

NOTE: this question was previously marked as a duplicate. It's subtly different, though: the other question asked what the difference is between the two syntaxes; whereas I know there's no difference in meaning, and I'm asking in that case why Java allows both.

Why does Java allow both

int x[];

and

int[] x;

when I declare an array?

The latter makes much more sense: the variable is called x, not x[], and its type is int[], not int. Why not just enforce this? Allowing two different syntaxes seems just to invite confusion and inconsistency. It even appears to make it possible to declare a two-dimensional array as

int[] x[];

which is bordering on unreadable.

Is it something borrowed from C? (Why would C do it that way round, anyway?)

Community
  • 1
  • 1
chiastic-security
  • 20,430
  • 4
  • 39
  • 67

2 Answers2

2

It was added to help C programmers get used to Java.

In Java int[] x; is the preffered way.

nana
  • 4,426
  • 1
  • 34
  • 48
2

At least from specification there is no explicit reason for the existence of both. However as follows both ways provide a certain flexibility. With one variable both declarations will provide you with an int array.

x and y are both arrays when:

int[] x, y;

x is an array and y not when:

int x[], y;

See also Oracle Java7 reference. They also say that mixed notation is not recommended noting done the following example:

float[][] f[][], g[][][], h[];  // Yechh!
fyr
  • 20,227
  • 7
  • 37
  • 53