After reading, I came to know that, arrays in Java
are objects. The name of the array is not the actual array, but just a reference. The new operator creates th
Please follow comments
int[] myArray = new int[5]; //memory allocated for 5 integers with nulls as values
int[] myArray= new int[]{5,7,3}; //memory allocated for 3 integers with values
int[] myArray= {5,7,3}; // same as above with different syntax memory allocated for 3integers with values.
Diffrerence between second and third style.
someX(new int[] {1,2,3}); // inline creation array style
someX(declaredArray); // using some declared array
someX({1,2,3}); //Error. Sorry boss, I don't know the type of array
private void someX(int[] param){
// do something
}
int[] myArray = new int[5];
In this we are specifying the length five to an array
int[] myArray= new int[]{5,7,3};
In this we are passing three elements and then specifying the length three.
int[] myArray= {5,7,3};
In this we are passing the element which will automatically specified the length three.
According to the bytecode of both cases, there is no difference. In both cases, 3 length spaces allocated and values are assigned.
int[] myArray= new int[]{5,7,3};
public class array.ArrayTest {
public array.ArrayTest();
Code:
0: aload_0
1: invokespecial #8 //
()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_3
1: newarray int
3: dup
4: iconst_0
5: iconst_5
6: iastore
7: dup
8: iconst_1
9: bipush 7
11: iastore
12: dup
13: iconst_2
14: iconst_3
15: iastore
16: astore_1
17: return
}
int[] myArray= {5,7,3};
public class array.ArrayTest {
public array.ArrayTest();
Code:
0: aload_0
1: invokespecial #8 //
()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_3
1: newarray int
3: dup
4: iconst_0
5: iconst_5
6: iastore
7: dup
8: iconst_1
9: bipush 7
11: iastore
12: dup
13: iconst_2
14: iconst_3
15: iastore
16: astore_1
17: return
}
This generates an array of size 5, with 5 null elements:
int[] myArray = new int[5];
If the values aren't something you know at compile time, this is probably more useful. E.g.
int[] myArray = new int[blah.size()];
for (int i = 0; i < blah.size() ; i++) {
myArray[i] = getFoo(blah.get(i));
}
If you knew the size ahead of time, you could use the other form.
int[] myArray = {blah.get(0), blah.get(1), blah.get(2)};
The following are equivalent (compile to the same bytecode), and generate an array with inferred size 3, with three elements, 5, 7, and 3. This form is useful if there are fixed set of values, or at least a fixed size set of values.
int[] myArray = new int[]{5,7,3};
int[] myArray = {5,7,3};
Otherwise you could accomplish the same thing with the longer form:
int[] myArray = new int[5];
myArray[0] = 5;
myArray[1] = 7;
myArray[2] = 3;
But this is unnecessarily verbose. But if you don't know how many things there are, you have to use the first form.