Initialize array of primitives

Muz picture Muz · May 27, 2012 · Viewed 17.6k times · Source

I am wondering,

What's exactly the difference between these two ways of initializing an array of primitives:

int[] arr1 = new int[]{3,2,5,4,1};

int[] arr2 = {3,2,5,4,1};

and which one is preferred ?

Answer

T.J. Crowder picture T.J. Crowder · May 27, 2012

There is none, they produce exactly the same bytecode. I think it may be that the second form wasn't supported in older versions of Java, but that would have been a while back.

That being the case, it becomes a matter of style, which is a matter of personal preference. Since you specifically asked, I prefer the second, but again, it's a matter of personal taste.