The difference between int [] variableName; and int variableName [];

Is there any difference between these two syntaxes for declaring an array in java?

int[] variableName; 

and

 int variableName[]; 

Which one is preferable?

+4
source share
7 answers

Although both syntaxes are equivalent, the syntax is int[] variableName; is preferred. Syntax int variableName[]; allowed only for ease of use by all C / C ++ programmers migrating to Java.

It can be argued that int[] x clearly states that the integer array is of type x, whereas in int x[] actual type is split into two parts: one before and the other after x , counting the integer as the type of x, which is an array that makes the ad less readable and potentially confusing for beginners.

The readability problem is compounded if the array has more dimensions, for example, all of these declarations are equivalent and valid:

 int x[][][]; int[] x[][]; int[][] x[]; int[][][] x; // this one is the easiest to read! 

Also note that the same considerations apply to all of these valid, equivalent method declarations (the return type is the same in all cases) - but again the latter is easier to read:

 int m() [][][] {return null;} int[] m() [][] {return null;} int[][] m() [] {return null;} int[][][] m() {return null;} // this one is the easiest to read! 
+13
source

The only case where the postfix syntax is essential is a very immaterial precedent:

 class ArrayShowcase { private int i, ints[], intints[][]; } 

Do we need such ads? I think we could live without them. I never needed this many hundreds of thousands of lines of code that I wrote in my professional career.

+4
source

As already mentioned, they are the same, and the first one is preferable. I would like to add that this is also necessary to match the appropriate use. If you change the code base that uses one of the two, stay with the same convention.

+1
source

They are semantically identical. The syntax int variablename [] was added only to help C programmers use java.

int [] the variable name is much preferable and less confusing.

Look here

+1
source

Both of them mean the same thing, therefore there is no difference syntactically. However, I have seen developers using one or the other.

0
source

I would use int [] var since it is more explicit. It tells the reader that it is an int array. If you have a [] next to the variable name, the user must scan along the line to see the type of this array. Personally, I (and most java programmers I know) used int []

0
source

The difference is conceptual for human reading. They define the same thing, but

int[] variableName keeps the type variableName compatible unlike

int variableName[] , which indicates that the array variable is of type int .

0
source

All Articles