Reputation: 557
We can declare and initialize a single dimensional array in one of the two ways
one we can declare using new keyword and in other we dont use new keyword. So how does memory allocation is done when we are not using the new keyword. Also, when should we go for new declaration when working with array in java
int []a = new int[5];
a[0]=1;
a[1]=2;
a[2]=3;
a[3]=4;
a[4]=5;
int []b = {1,2,3,4,5}
Upvotes: 1
Views: 1173
Reputation: 54639
As already mentioned in the comments: There is no difference in practice. So the difference is mainly syntactical.
This may be a few more details than you have been asking for, but: It is not entirely syntactical. Interestingly, the bytecode is slightly different. Consider this class:
class ArrayInit
{
public static void main(String args[])
{
initA();
initB();
}
public static void initA()
{
int []a = new int[5];
a[0]=1;
a[1]=2;
a[2]=3;
a[3]=4;
a[4]=5;
}
public static void initB()
{
int[] b = {1,2,3,4,5};
}
}
Compiling it and disassembling the resulting class
file with
javap -c ArrayInit
prints the resulting byte code of both methods. A side-by-side comparison of the byte codes of both methods is shown here:
public static void initA(); public static void initB();
Code: Code:
0: iconst_5 0: iconst_5
1: newarray int 1: newarray int
3: astore_0
4: aload_0 3: dup
5: iconst_0 4: iconst_0
6: iconst_1 5: iconst_1
7: iastore 6: iastore
8: aload_0 7: dup
9: iconst_1 8: iconst_1
10: iconst_2 9: iconst_2
11: iastore 10: iastore
12: aload_0 11: dup
13: iconst_2 12: iconst_2
14: iconst_3 13: iconst_3
15: iastore 14: iastore
16: aload_0 15: dup
17: iconst_3 16: iconst_3
18: iconst_4 17: iconst_4
19: iastore 18: iastore
20: aload_0 19: dup
21: iconst_4 20: iconst_4
22: iconst_5 21: iconst_5
23: iastore 22: iastore
23: astore_0
24: return 24: return
One can see that basically, in the first variant, which uses new
and assigns the array elements individually, the reference to the array is pulled on the stack using aload_0
instructions. In the direct initialization, the reference is already on the stack, and just duplicated with dup
instructions.
However, the difference is negligible, and in the end, does not matter at all: When extending the program slightly so that the methods are called a few thousand times, and examining the resulting machine code with java -server -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly
shows that the machine code of both methods will in fact be identical eventually.
Upvotes: 1