Muz
Muz

Reputation: 267

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 ?

Upvotes: 26

Views: 25493

Answers (7)

Pedro Blandim
Pedro Blandim

Reputation: 380

Adding to @Paul Bellora's answer, only the second option will work if you're trying to initialize a primitive array using ternary operator

int[] arr1 = false ? {} : {1,2}; // doesn't work
int[] arr2 = false ? new int[]{} : new int[]{1,2}; // works

Upvotes: 0

David Chen
David Chen

Reputation: 41

In your case, these two styles end up same effect, both correct, with the second one more concise. But actually these two styles are different.

Remember arrays in java are fixed length data structures. Once you create an array, you have to specify the length.

Without initialization, the first case is

int[] arr1 = new int[5];

The second case it would be

int[] arr2 = {0,0,0,0,0};

You see the difference? In this situation, the first style is preferred as you don't have to type all those default initial values manually.

To me, the only big difference between the two styles is when creating an array without explicit initialization.

Upvotes: 4

Alex Lockwood
Alex Lockwood

Reputation: 83303

In this case, the second one because it's prettier and less verbose :)

Upvotes: 1

goat
goat

Reputation: 31813

useful in this situation

void foo(int[] array) {

}

calling with a literal

// works
foo(new int[]{5, 7})

//illegal
foo({5, 7})

Upvotes: 1

whileone
whileone

Reputation: 2805

There is no difference between the two statements. Personally speaking, the second one is preferred. Because you have all the elements specified in the braces. The compiler will help you to compute the size of the array.

So no need to add int[] after the assignment operator.

Upvotes: 7

Paul Bellora
Paul Bellora

Reputation: 55213

As others have mentioned, they are equivalent and the second option is less verbose. Unfortunately the compiler isn't always able to understand the second option:

public int[] getNumbers() {
   return {1, 2, 3}; //illegal start of expression
}

In this case you have to use the full syntax:

public int[] getNumbers() {
   return new int[]{1, 2, 3};
}

Upvotes: 9

T.J. Crowder
T.J. Crowder

Reputation: 1074238

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.

Upvotes: 19

Related Questions