I have recently been thinking about the difference between the two ways of defining an array:
int[] array
int array[]
Is there a difference?
Java Arrays. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. To declare an array, define the variable type with square brackets: String[] cars; We have now declared a variable that holds an array of strings. To insert values to it, we can use an array literal - place ...
Normally, an array is a collection of similar type of elements that have a contiguous memory location. Java array is an object which contains elements of a similar data type. It is a data structure where we store similar elements.
An array declaration has two components: the type and the name. type declares the element type of the array. The element type determines the data type of each element that comprises the array.
It merely tells the compiler that this variable (intArray) will hold an array of the integer type. To link intArray with an actual, physical array of integers, you must allocate one using new and assign it to intArray. Instantiating an Array in Java. When an array is declared, only a reference of array is created.
They are semantically identical. The int array[]
syntax was only added to help C programmers get used to java.
int[] array
is much preferable, and less confusing.
There is one slight difference, if you happen to declare more than one variable in the same declaration:
int[] a, b; // Both a and b are arrays of type int
int c[], d; // WARNING: c is an array, but d is just a regular int
Note that this is bad coding style, although the compiler will almost certainly catch your error the moment you try to use d
.
There is no difference.
I prefer the type[] name
format at is is clear that the variable is an array (less looking around to find out what it is).
EDIT:
Oh wait there is a difference (I forgot because I never declare more than one variable at a time):
int[] foo, bar; // both are arrays
int foo[], bar; // foo is an array, bar is an int.
No, these are the same. However
byte[] rowvector, colvector, matrix[];
is equivalent to:
byte rowvector[], colvector[], matrix[][];
Taken from Java Specification. That means that
int a[],b;
int[] a,b;
are different. I would not recommend either of these multiple declarations. Easiest to read would (probably) be:
int[] a;
int[] b;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With