Mellon Mellon - 7 months ago 18
Java Question

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?


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