chiastic-security
chiastic-security

Reputation: 20520

Why does Java allow both int x[] and int[] x?

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?)

Upvotes: 0

Views: 164

Answers (2)

fyr
fyr

Reputation: 20859

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!

Upvotes: 2

nana
nana

Reputation: 4481

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

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

Upvotes: 2

Related Questions