Search code examples
javaarraysprimitive

Initialize array of primitives


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 ?


Solution

  • 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.