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 ?
To provide initial object references or primitive values other than the default, you have to address each element in the array. In the following code, we declare and create an array of Rectangle objects, and then create the Rectangle objects for each element: 1. Rectangle hotSpots[] = new Rectangle[10]; 2.
The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.
Answer and Explanation:Java arrays can store primitive types and strings, but cannot store any other type of object other than Strings.
No, arrays are not primitive datatypes in Java. They are container objects which are created dynamically. All methods of class Object may be invoked on an array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With