3

Please explain to me what the difference is between the two declaration of an array

int[] a = {5, 7, 8, 9, 6};

and

int[] arr = new int[]{5, 7, 8, 9, 6};

Is it something like in first statement there is no memory allocation and in the second memory is allocated to each element?

Also, why does the below declaration result in an error?

int[] arr = new int[5]{5, 7, 8, 9, 6};
Makoto
  • 96,408
  • 24
  • 164
  • 210
abhishek gupta
  • 333
  • 1
  • 10
  • This isn't a duplicate as this question asks the difference between these two syntaxes, not how to create an array. – Makoto Feb 28 '15 at 20:18

3 Answers3

2

They may look similar, and they may behave similarly, but they are indeed different.

The first declaration you have is an array initializer. It can only be used when you're declaring a field or variable (as you are with int[] a = {1, 2, 3, 4, 5, 6}), or as part of the second form, an array creation expression.

The array initializer requires a reifiable type in order for it to be valid syntax. This means that you cannot use it to create a generic array. As an example:

public class Example<T> {

    public void doStuff(T first, T second, T third) {
        // Invalid; T is not a reifiable type
        T[] stuff = {first, second, third};
    }

    public void doStuff(int first, int second, int third) {
        // Valid; int is reifiable
        int[] stuff = {first, second, third};
    }
}

The second declaration that you have is an array creation expression. It allows for several forms of declaring an array. It also allows you to create generic arrays through some rather forced casting.

To the question of why the third syntax is invalid: below is an excerpt of the ArrayCreationExpression.

  ArrayCreationExpression:
      new PrimitiveType DimExprs Dims (optional)
      new ClassOrInterfaceType DimExprs Dims (optional)
      new PrimitiveType Dims ArrayInitializer 
      new ClassOrInterfaceType Dims ArrayInitializer

  DimExprs:
      DimExpr
      DimExprs DimExpr

  DimExpr:
      [ Expression ]

  Dims:
      [ ]
      Dims [ ]

Effectively, the reason the syntax new int[5]{1, 2, 3, 4, 5} is invalid is because of the above.

int[5]{1, 2, 3, 4, 5} contains a DimsExpr, which is the [5] piece, and an ArrayInitializer, which is the {1, 2, 3, 4, 5} piece. The above language specification does not allow for both a DimsExpr(s) and an ArrayInitializer to be declared together.

Community
  • 1
  • 1
Makoto
  • 96,408
  • 24
  • 164
  • 210
0

No difference between the two first declarations. The last declarations specifies the length of the array twice. I assume that it is invalid to avoid having the compiler match the two specified sizes.

Tarik
  • 9,314
  • 1
  • 19
  • 35
  • This isn't correct. It's really a matter of the language lexer supporting the syntax. If the language doesn't support the syntax, the supposition as to what could happen to a supposedly declared object with that syntax is irrelevant. – Makoto Feb 28 '15 at 20:58
  • For software engineering this is not irrelevant. Any java architect will tell you that java tries to keep its syntax aligned with good practices, that is the same reason we got an enhanced <> expression, after we had one already for the same propose. – Victor Feb 28 '15 at 21:01
  • @Victor I did not imply anywhere that it was irrelevant. On the contrary, it would take more efforts to solve potential ambiguities. – Tarik Mar 01 '15 at 02:00
  • @Makoto Yes, any syntax can be supported, including ones that are troublesome. The Java team has obviously made the choice to avoid potential ambiguities by preventing overspecifying the array length parameter. – Tarik Mar 01 '15 at 02:03
  • Sorry about the misunderstand @Tarik, I was talking about his comment, not you answer. – Victor Mar 01 '15 at 07:32
0

There is no difference between the first two, you will allocate memory for them as they both require.

The third one, however, is incorrect as it has duplicated information. If you are using {x,y,z}, the number of elements is implied and you don't need or should repeat this information on [number_elements]. Especially because those peaces of information could be incoherent as: [2]{x,y,z}

from oracle's docs pages:Here the length of the array is determined by the number of values provided between braces and separated by commas

That is also why it is perfectly fine to do int[]{5,7,8,9,6}

Now, if you don't have the initial values on a {}, there is no information; thus the need for [number].

Victor
  • 3,070
  • 3
  • 32
  • 51
  • There's no duplicated information in the second declaration. The language lexer just doesn't support it. – Makoto Feb 28 '15 at 20:36
  • Yes there is, if you look at the {}, the number of element is implied as you can count, like any array you create, they have a length field. it is not explicated but is there. – Victor Feb 28 '15 at 20:43
  • from docs:Here the length of the array is determined by the number of values provided between braces and separated by commas. – Victor Feb 28 '15 at 20:44
  • you are right, there is no write way, I as just saying why is not a valid syntax, rather then just say it is not supported – Victor Feb 28 '15 at 20:46
  • But the reason that it's not a valid syntax is *because* the syntax is not supported. That's really all I was getting at here. You can take a look at my answer and click through the JLS references to get a better understanding of that. – Makoto Feb 28 '15 at 20:47
  • your answer is valid, but is a simple it is because it is. you used the grammar to say that the syntax is not valid. well, the grammar says that, indeed, but someone wrote it for a reason.. sorry to disagree with you, I see your point, but our answers do not conflict if you think about it, we got different approaches. BTW, dont need to tell people to go study, this is kind of rude, discussion is always good. – Victor Feb 28 '15 at 20:52
  • @Tarik, used the same approach to answer, in a shorter sentence I believe. – Victor Feb 28 '15 at 20:57
  • @Makoto We **obviously** know the syntax is not supported since we are getting a syntax error. The question is about the reason for not supporting such syntax and Victor gave an elaborated explanation that I believe is valid. – Tarik Mar 01 '15 at 02:08