1

Is there a significant difference between these two lines of code?

int[] array = new int[]{1,2,3}
int[] array = {1,2,3}

If I had to guess, the same constructor is called implicitly in the second version, making them identical.

Edit: This question was explored previously here but with default values. My question regarded the initialization of an array with non-default values.

and
  • 13
  • 4
  • Have you tried disassembling the byte-code and see if there are any noticeable difference? – Veera Dec 18 '17 at 03:59

1 Answers1

2

Just out of curiosity, I did de-compile the class with following methods

public void arrayTest1(){
    int[] array = new int[]{1,2,3};
}

public void arrayTest2(){
    int[] array = {1,2,3};  
}

Here is the result related to them.

  public void arrayTest1();
    Code:
       0: iconst_3
       1: newarray       int
       3: dup
       4: iconst_0
       5: iconst_1
       6: iastore
       7: dup
       8: iconst_1
       9: iconst_2
      10: iastore
      11: dup
      12: iconst_2
      13: iconst_3
      14: iastore
      15: astore_1
      16: return

  public void arrayTest2();
    Code:
       0: iconst_3
       1: newarray       int
       3: dup
       4: iconst_0
       5: iconst_1
       6: iastore
       7: dup
       8: iconst_1
       9: iconst_2
      10: iastore
      11: dup
      12: iconst_2
      13: iconst_3
      14: iastore
      15: astore_1
      16: return

Both the statements essentially look the same de-compiled.

Pshemo
  • 113,402
  • 22
  • 170
  • 242
Veera
  • 266
  • 1
  • 8
  • Thank you! This is good to know. This was one of the comments on my original post: "Have you tried disassembling the byte-code and see if there are any noticeable difference? – Veera". Is this what you did? How is this done? – and Dec 18 '17 at 05:12
  • [javap](https://docs.oracle.com/javase/7/docs/technotes/tools/windows/javap.html) is provided by Java distribution that allows your disassemble the byte-code. In this case, I had run with -c option – Veera Dec 18 '17 at 05:38
  • Thanks [Pshemo](https://stackoverflow.com/users/1393766/pshemo) for adding a more broken down piece of code. – Veera Dec 18 '17 at 05:38