Mellon
Mellon

Reputation: 38912

difference between these 2 ways of initializing an simple array

In java, I can initialize an array with predefined content either by :

int[] myArr = new int[]{1,2,3};

Or by :

int[] myArr = {1,2,3};

Essentially, is there any difference between these two ways ? Are they completely identical in Java ? Which way is better and why?

Upvotes: 6

Views: 186

Answers (5)

j2e
j2e

Reputation: 566

Both ways generate exactly the same result. Both are arrays of length 3 with predefined values. The second one is just shorter. The second method of declaring an array is better if you think that you need less time to write that code.

In the case you need to use that array to directly pass it to a method you should use the first one:

//Correct
someMethod(new int[]{1,2,3});

//Incorrect
someMethod({1,2,3});

But if your goal is only to declare and initialize the array in a variable either ways are correct:

int[] myArr = new int[]{1,2,3}; //Correct
int[] myArr = {1,2,3}; //Also Correct

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 122026

In your case there is no difference.

There will be a difference when you are not assigning your array to variable and doing inline creation.

for example, conside there is method, which takes an array as argument.

  private  void someX(int[] param){
              // do something
          }

Your case:

  someX(myArr);     // using some declared array .I.e your case

Now see the difference while calling it in other cases.

      someX(new int[] {1,2,3}); //  yes, compiler satisfied.
      someX({1,2,3});     //Error. Sorry boss, I don't know the type of array

Upvotes: 5

Hussain Shabbir
Hussain Shabbir

Reputation: 15035

int[] myArr = new int[]{1,2,3};

Here it means you are initializing the three variable which will create the length of array 3

int[] myArr = {1,2,3};

Here it means you are initializing the three variable which will by default create the length of array 3

Upvotes: 0

An SO User
An SO User

Reputation: 25028

No, the first and second are the same. The second is just syntactic sugar. Your end result is the same.

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213401

is there any difference between these two ways ? Are they completely identical in Java ?

No there is no difference. Both of them will create an array of length 3 with the given values.

The 2nd one is just a shorthand of creating an array where you declare it. However, you can't use the 2nd way of creating an array, at any other place than the declaration, where the type of array is inferred from the declared type of array reference.

Upvotes: 5

Related Questions