Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between these 2 ways of initializing an simple array

Tags:

java

arrays

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?

like image 902
Mellon Avatar asked Oct 29 '13 12:10

Mellon


2 Answers

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
like image 71
Suresh Atta Avatar answered Oct 21 '22 05:10

Suresh Atta


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.

like image 42
Rohit Jain Avatar answered Oct 21 '22 06:10

Rohit Jain