Click here to Skip to main content
15,890,043 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hello!

Is there any difference between the two array declaration in Java?


Java
int[] myIntArray = {1,2,3};

int[] myIntArray = new int[]{1,2,3};



I know that the first array is stored dinamycally in memory, but what about the first one?
Should I use one or the other?
Posted

The top one is an array-literal (or constant array), the second one is an array declaration. When you assign immediately there's no difference, they're both allocated dynamically in exactly the same way.

The only difference is that a array-literal can only be used during initialization of an array variable, meaning you can't use the literal syntax to re-assign the value of an array.
Java
// Here, these are equivalent
int[] a = new int[] { 1, 2, 3};
int[] b = {1, 2, 3};

// They differ during re-assignment
a = new int[] { 4, 5, 6}; // This is fine, a now "points" to a new array.
b = {4, 5, 6}; // Will not compile!

Hope this helps,
Fredrik
 
Share this answer
 
Comments
dliviu 1-Mar-15 7:25am    
Thank you very much!
Fredrik Bornander 1-Mar-15 7:38am    
Glad I could help.
There is no difference.
—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900