tags:

views:

85

answers:

2

While declaring array we can use brackets any side of the identifier but in the case:

int[] k,i;

and

int k[],i;

It will be considered in two different ways. That is first one creates two arrays k and i. that second one creates an array k and a normal variable i. What is this behavior?

EDIT: in java usually we prefer first type of declaration. but in this case we cant create an array and a primitive variable in the single statement.

+3  A: 

My guess is the following:

The declaration int[] k is more logical, because it declares k to be an array of int. Therefore, it is the preferred (?) style in Java.

int k[], on the other hand, was the C way of declaring this array (K&R had a different philosophy when it came to declaration syntax – they wanted declarations to mimic access to the variable) and to ease the transition for C programmers, this syntax was also allowed – no harm done.

Now, in your above statement you have chained two declarations. In the first case, both variables are declared with the same type – which is clearly int[]. However, in the second code this behaviour would be counter-intuitive (and also different from C’s behaviour), and therefore has other semantics.

Keep in mind that this is purely a guess.

Konrad Rudolph
It's indeed the preferred style. http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html says *However, convention discourages this form; the brackets identify the array type and should appear with the type designation.*
BalusC
+2  A: 

Think of it like this:

(int[]) k, i

int (k[]), (i)

In the first example, the brackets are associated with the int keyword, specifying that you want to create int arrays. In the second, you specify type int, then declare an array of ints k, and an int i.

Paul Rayner