1

I am a beginner to Java and have a question wrt to how arrays can be declared in Java and was looking back through some Stack Overflow questions.

In the answer to one question it suggests that there are three ways to declare an integer array.

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

I understand the concept but I am a little confused wrt to the last two examples:

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

What is the difference between the two? - can anyone give me a practical example of when one is better than the other and for which used case.

Dharman
  • 21,838
  • 18
  • 57
  • 107
  • 1
    https://stackoverflow.com/questions/1200621/how-do-i-declare-and-initialize-an-array-in-java The comments on this question should help! – Xhuliano Brace Dec 31 '19 at 18:04
  • 1
    Given that the OP is quoting code from the accepted answer to [that question](https://stackoverflow.com/questions/1200621/how-do-i-declare-and-initialize-an-array-in-java), I guess that question doesn't answer them. :-) – T.J. Crowder Dec 31 '19 at 18:07
  • 1
    I have temporarily closed this question with a link to another question here on Stack Overflow. Let us know if there is anything you need clarified from that question and I can reopen this one. – Code-Apprentice Dec 31 '19 at 18:08

1 Answers1

0

I understand the concept but I am a little confused wrt to the last two examples:

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

They do exactly the same thing. The second form is slightly older than the first, but the first form has been supported for many years now.

Just for completeness, the difference between those and int[] myIntArray = new int[3]; is that with the two quoted above, the array is declared, created, and filled with the initial values 1, 2, and 3. With int[] myIntArray = new int[3];, the array is declared and created with just default values (0, 0, and 0).

Community
  • 1
  • 1
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
  • thank you - but is there a used case when you would use the third example over the second or is it simply a matter of personal preference. –  Dec 31 '19 at 18:20
  • 1
    @timber - Oh absolutely: If you didn't know (yet) what values you wanted to put in the array. Creating the array with default values (`int[] myIntArray = new int[3];`) is probably the more common case than knowing in advance what values you want to have in it. :-) – T.J. Crowder Dec 31 '19 at 18:27