Search code examples
javaarraysparametersconstructorinitializer

Double brace initializer and array


I have a method having an array parameter like:

public static void foo(int[] param) {
    // Some code
}

And also I can call the method by writing like

foo(new int[3]);

Normally, we declare and initialize an array by new operator or double braces initializer like {1, 2, 3}. For example, int[] foo = new int[3]; or int[] foo = {1, 2, 3};.

But it's impossible to use double brace initializer as a parameter for a method. {} is only available for creating an array object.

And here is my question: Are there any differences between new operator and {}? If there is, what is it?


Solution

  • The {} as part of a int foo[] = {1, 2, 3}; is what is termed as brace initialization, and is a shortcut for int foo[] = new int[]{1, 2, 3}; because the new int[] can be inferred from the left hand side.

    In the second case foo({1, 2, 3}); no inference of what you intend can be determined as there is no hint as to what the {1, 2, 3} means, so the compiler complains.

    When you rewrite it as foo(new int[]{1, 2, 3}); you're telling the compiler what the item in {} is meant to represent.

    The compiler won't (and does not try) to auto-interpret the {} expression until it matches - that would lead to potential ambiguities.

    There is also this question, which seems to cover exactly the same ground.

    As mentioned by @benzonico, it is part of the language specification as to this being a supported syntax, which doesn't include it being used in the invocation of a method.