2
int[] arr = {1, 2, 3};

arr = {1, 2, 3} //Error
arr = new int[] {1, 2, 3}; //No Error

So my question is, why is that so? I mean wheres the difference between line 2 and line 3?

Djeurissen
  • 377
  • 5
  • 15
  • 1
    That's just how the Java language is specified. Whether or not you think the language could or should support the erroneous syntax, it simply doesn't. – Andy Turner Sep 10 '16 at 06:26
  • Not everything that the fathers of Java language thought up does make 100% sense. As I can't even think of a reason why these rules would make parsing easier for example. – GhostCat Sep 10 '16 at 06:28
  • 1
    Is this java or C#? Please don't tag the question with both – Rob Sep 10 '16 at 06:29
  • 1
    java and c# are different languages. Tag your question with one language only. – Erwin Bolwidt Sep 10 '16 at 06:29
  • 1
    @GhostCat I think it is because of the covariance of arrays: since you could assign a `String[]` to a `Object[]`, you can't necessarily infer the element type of the array to create from the elements on the RHS and the element type of the LHS of the assignment. But that's for reference types; seems like you could with primitives. – Andy Turner Sep 10 '16 at 06:33

1 Answers1

3

That is how java or C# works buddy, can't really complain on this.. if we come to programming language semantics, line 2 introduces some ambiguity which is not really desired, and if we think about the really advanced stuff like the parse tree that needs to be constructed for a statement like the line 2, we are running into great trouble.

read some thing about parsers if you like link to parse trees

Infamous
  • 744
  • 11
  • 25