0

The following show different ways of instantiating and returning a primitive array. However, for some reason, the last one doesn't work. Is there a valid explanation for this inconsistency? Why doesn't the last block work?

Block 1

    int[] a = new int[] {50};
    return a;    // works fine

Block 2

    int[] a = {50};
    return a;    // works fine

Block 3

    return new int[] {50};    // works fine

Block 4

    return {50};   // doesn't work
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Calculus5000
  • 427
  • 6
  • 17

1 Answers1

3

Why doesn't the last block work?

Because an array initializer (JLS 10.6) is only valid in either a variable declaration, as per your first and second blocks, or as part of an array creation expression (JLS 15.10.1), as per your third block.

Your fourth block isn't either a variable declaration or an array creation expression, so it's not valid.

Note that this isn't specific to primitive arrays at all - it's the same for all arrays.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Great, thanks for this! I don't really see how it applies as you can't really omit the `new` in `List = new ArrayList<>();`? – Calculus5000 Mar 11 '15 at 13:53
  • @Calculus5000: Well that's not for arrays, is it? Basically the syntax for arrays isn't exactly the same as the syntax for other things. – Jon Skeet Mar 11 '15 at 13:54
  • Oh ok. So it only works for primitive arrays then? Because I got confused by `Note that this isn't specific to primitive arrays at all - it's the same for all arrays.` In Java, I understand that arrays and primitive arrays are synonymous, right? – Calculus5000 Mar 11 '15 at 13:57
  • 1
    @Calculus5000: No, not at all. For example: `String[] x = { "foo", "bar" };`. `String` isn't a primitive type. – Jon Skeet Mar 11 '15 at 13:59