Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize array of primitives

Tags:

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 ?

like image 216
Muz Avatar asked May 27 '12 15:05

Muz


People also ask

How do you initialize a primitive array in Java?

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.

How do you initialize an array?

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.

Can arrays hold primitives?

Answer and Explanation:Java arrays can store primitive types and strings, but cannot store any other type of object other than Strings.

Can arrays have primitive data types?

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.


1 Answers

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.

like image 125
T.J. Crowder Avatar answered Nov 11 '22 01:11

T.J. Crowder