Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between int[] variableName; and int variableName[];

Is there any difference between between these two array declaration syntax in java?

int[] variableName; 

and

int variableName[];

Which one is preferred?

like image 869
Adi Avatar asked Aug 25 '12 13:08

Adi


People also ask

What is the difference between int array [] and int [] array?

What is the difference between int[] a and int a[] in Java? There is no difference in these two types of array declaration. There is no such difference in between these two types of array declaration. It's just what you prefer to use, both are integer type arrays.

What is the difference between int and int [] in Java?

Sr. No. A int is a data type that stores 32 bit signed two's compliment integer. On other hand Integer is a wrapper class which wraps a primitive type int into an object.

What is an int [] in Java?

The Java int keyword is a primitive data type. It is used to declare variables. It can also be used with methods to return integer type values. It can hold a 32-bit signed two's complement integer.

What is the difference between integer class and int data type?

The major difference between an Integer and an int is that Integer is a wrapper class whereas int is a primitive data type. An int is a data type that stores 32-bit signed two's complement integer whereas an Integer is a class that wraps a primitive type int in an object.


Video Answer


1 Answers

Although both syntaxes are equivalent, the int[] variableName; syntax is preferred. The int variableName[]; syntax is allowed just for making comfortable all the C/C++ programmers transitioning to Java.

One could argue that int[] x clearly states that integer array is the type of x, whereas in int x[] the actual type is split in two parts, one before and the other after the x variable, reading like integer is the type of the variable x which is an array making the declaration less readable and potentially confusing to a newcomer.

The readability problem is exacerbated 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 notice that the same considerations apply to all these valid, equivalent method declarations (the return type is the same in all cases) - but once again the last one is simpler 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!
like image 94
Óscar López Avatar answered Sep 19 '22 00:09

Óscar López